Look at the first step of jquery source code, for the creation of jquery objects to see the foggy, pondering half a day finally a little feeling, in this record
The first way:
var A = function () {
return a.prototype.init ();
}
A.prototype = {
Init:function () {
This.age = 50;
Console.log (this);
return this;
},
age:100
}
Console.log (A () = = = new A ());
1. analysis of why the result is true
the a.prototype.init () function is called internally by A ()
The constructor is called inside New A (), and its constructor is function () {return a.prototype.init ();} , the a.prototype.init () function is also called
2. Analyze What the A.prototype.init () function returns
That depends on this , judging who this is, and we're going to parse it when the function is called, because it's called as a property of the prototype object, so this is the prototype object A.prototype
This way of creating, no matter how many times A () You call, they are all the same objects returned, so the modification of the B object affects the A object, see
var a = a ();
var B = A ();
Console.log (A.age);
Console.log (B.age);
B.age = 22;
Console.log (A.age);
Console.log (B.age);
So how to solve this problem, then the second way, it is the way jquery used
The second way
var A = function () {
Return new A.prototype.init();//①
}
A.prototype = {
Init:function () {
This.age = 50;
Console.log (this);
return this;
},
age:100
}
a.prototype.init.prototype = A.prototype;//②
var a = new A ();
var B = new A ();
Console.log (A===B);
Console.log (A.age);
Console.log (B.age);
B.age = 22;
Console.log (A.age);
Console.log (B.age);
Analysis of the ① and ②
① in new A.prototype.init () has done three things
Create an empty object var obj = {};
the Obj object property _proto_ points to the prototype of the function a.prototype.init;
Replace this of the A.prototype.init function with the obj object, in the call to the a.prototype.init function, A.prototype.init.call (obj), and returns the new object
Because the prototype of the object returned by ① is a.prototype.init.prototype, it has nothing to do with a.prototype, so that the newly returned object can inherit from the A.prototype , so ② let a.prototype.init.prototype point to a.prototype
Therefore, the second way is to create an instance, and ensure that their respective scopes are independent.
No new build of JavaScript