constructor, constructors, we are not unfamiliar with this name,constructor always point to the constructor that created the current object.
One thing to note here is that each function has a prototype attribute, and this prototype constructor points to the function, which is unexpected when we modify the prototype of this function. Such as
function Person (name,age) {
this.name = name;
This.age = age;
}
Person.prototype.getAge = function () {return
this.age;
}
Person.prototype.getName = function () {return
this.name;
}
var p = new Person ("Nicholas",);
Console.log (P.constructor); Person (name, age)
Console.log (P.getage ());//18
Console.log (P.getname ());//nicholas
But if this is the case:
function Person (name,age) {
this.name = name;
This.age = age;
}
Person.prototype = {
getname:function () {return
this.name;
},
getage:function () {
return This.age
}
}
var p = new Person ("Nicholas",);
Console.log (P.constructor); Object ()
Console.log (P.getage ());//18
Console.log (P.getname ());//nicholas
The result constructor changed.
The reason is that prototype itself is also an object, and the code above is equivalent to
Person.prototype = new Object ({
getname:function () {return
this.name;
},
getage:function () { return
this.age;
}
});
Because constructor always points to the constructor that creates the current object, it is not difficult to understand that the above code p.constructor Output is object.
What about the constructor that changed the prototype and wanted it to point to person? Simply, assign a value directly to the Person.prototype.constructor:
Person.prototype = {
Constructor:person,
getname:function () {return
this.name;
},
getage: function () {return
this.age;
}
}
This article on the constructor of JavaScript is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.