By invoking the function with the new operator to reach the object this is worth the purpose, the constructor returns the object it created to us.
Directly on the code
To create a constructor function
function Gadget (name, color) {
THIS.name = name;//Add Property
This.color = color;
This.whatareyou = function () {//Add method
return This.color + "" + this.name;
}
}
Another way to add properties and methods, through the prototype property of the constructor function, is to add
Gadget.prototype.price = 100;//Prototype Properties
Gadget.prototype.rating = 3;
Gadget.prototype.getInfo = function () {
Return this.price+ "" +this.rating;
}
/* Shorthand
Gadget.prototype = {
PRICE:100,
Rating = 3,
GetInfo = function () {
return This.price + "" +this.rating;
}
}
*/
To create a new object using the constructor
var newtoy = new Gadget (' webcam ', ' black ');
newtoy.name;//
---->>webcam
The object is passed by reference, that is, the object entity created does not have a copy of its own prototype, and the value passing produces a copy
Gadget.prototype.get = function (what) {
return This[what];
}
Newtoy.name
If the name attribute exists in the properties and prototypes of the object itself, the property of the object itself takes precedence over the properties of the prototype
The Name property in the prototype is used when you delete the (delete newtoy.name) object property
js--using constructor functions to create new objects and operations