Read the question of "js Advanced programming"?
Chapter 6: there is such a dynamic prototype pattern in the way objects are created
function Persion() {
this.name="wyq";
this.friends=["a", "b", "c"];
//??? new
if(typeof this.sayName !=="function"){
this.sayName = function () {
console.log("friends",this.friends);
}
}
}
can"t you just write it this way?
function Persion() {
this.name="wyq";
this.friends=["a", "b", "c"];
}
Persion.prototype = {
sayName: function () {
console.log("this.name", this.name);
},
};
the function of a piece of code depends on the environment in which it is used. The implementation of a function may be written in many ways
the following is our most common and most commonly used way of writing, so what's the difference between the above code and the following code?
the difference is the above code. The sayName attribute acts on the child object, while the following code acts on the parent
.
if the above code is modified
function Persion(hasSayName) {
//...
if(hasSayName && typeof this.sayName !=="function"){
//...
}
}
var p1 = new Persion
var p2 = new Persion(true)
in this way, the purpose of the code is very clear
in fact, the goal of both parties is that after creating an object, the instance has the ability to sayName ()
what's the difference:
the sayName created in this way is created on the instance after the new Persion instance
function Persion() {
this.name="wyq";
this.friends=["a", "b", "c"];
//??? new
if(typeof this.sayName !=="function"){
this.sayName = function () {
console.log("friends",this.friends);
}
}
}
the sayName created in this way is created directly on the Persion constructor
function Persion() {
this.name="wyq";
this.friends=["a", "b", "c"];
}
Persion.prototype = {
sayName: function () {
console.log("this.name", this.name);
},
};
to sum up: one is created on the instance, the other is created on the constructor