When I looked at the first step of jquery source code, I was confused about the creation of jquery objects. After thinking about it for a long time, I finally felt it. Here I record it
The first method:
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.Analyze why the result is true
The A.prototype.init() function is called internally by A()
new A() will call the constructor internally, and its constructor is function(){return A.prototype.init();}, and the same call is the A.prototype.init() function
2.Analysis what the A.prototype.init() function returns
It depends on this, determine who this points to. We need to analyze it when calling the function. Since it is called as the attribute of the prototype object, this is the prototype object A.prototype
In this way of creation, no matter how many times you call A(), they are actually the same object returned, so the modification of object b will affect object a, see the figure below
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);console.log(b.age);
So how to solve this problem? Let’s talk about the second method, which is also the method used by jquery.
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);console.log(b.age);
Analysis of ① and ②
①In new A.prototype.init() mainly does three things
Create an empty object var obj = {};
obj object property_proto_ points to the prototype of function A.prototype.init;
Replace this in A.prototype.init function with obj object, call A.prototype.init function, A.prototype.init.call(obj), and return the new object
Because ① the prototype of the returned object is A.prototype.init.prototype, it has nothing to do with A.prototype. In order to make the newly returned object inherit from A.prototype, ② Let A.prototype.init.prototype point to A.prototype
Therefore, the second method is to create an instance, and ensure that each of its own scope is independent.
The above is a detailed explanation of the new-free construction example of Javascript introduced to you by the editor. I hope it will help you. If you want to know more information, please pay attention to the Wulin.com website!