Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the constructor of javascript

Shulou Source: shulou.com Published: 2022-05-31 10:40:13 09月23日 Update

This article introduces the knowledge of "how to use the constructor of javascript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Constructor considerations:

1. Default function initials are capitalized

two。 The constructor does not show anything that is returned. The new operator automatically creates the given type and returns them, and when the constructor is called, new automatically creates the this object, and the type is the constructor type.

3. You can also display the call to return in the constructor. If the returned value is an object, it is returned instead of the newly created object instance. If the returned value is of an original type, it is ignored and the newly created instance is returned.

FunctionPerson (name) {

This.name=name

}

Varp1=newPerson ('John')

Equivalent to:

Functionperson (name) {

Objectobj=newObject ()

Obj.name=name

Returnobj

}

Varp1=person ("John")

What about the constructor?

1. Because the constructor is also a function, it can be called directly, but its return value is undefine, so the this object in the constructor is equal to the global this object. This.name is actually about creating a global variable, name. In strict mode, an error occurs when you call the Person constructor through new.

two。 You can also use the Object.defineProperty () method in the constructor to help us initialize:

FunctionPerson (name) {

Object.defineProperty (this, "name" {

Get:function () {

Returnname

}

Set:function (newName) {

Name=newName

}

Enumerable:true,// can be enumerated. Default is false.

Configurable:true// configurable

})

}

Varp1=newPerson ('John')

That's all for the content of "how to use the constructor of javascript". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Function object type global content instance that is more knowledge primitive practical successful next thing use item variable dilemma uppercase letter Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno MariaDB Redmi macOS Shulou Tech Info