This problem actually comes from when analyzing the jQuery source code, I saw thatvar ret = jQuery.merge(this.constructor(), elems );, where this.constructor() returns The empty instance object created by the init method. Therefore, I am confused about the direction of this.
The following is the test code:
function Person() { this.name = 'ddadaa'; console.log(this); } var p1 = new Person(); p1.constructor(); // Person {name: "ddadaa"} var p2 = p1.constructor; p2(); //打印的是window
Why is it that when constructor() is called directly here, the pointer of this changes and a new object is automatically created? Does the internal implementation of the constructor() method have an impact on this?
This has nothing to do with the internal implementation of the
constructor()method. It is actually a problem pointed to by this within the function.When the function is called as a property of the object,
thispoints to the object;When the function is called directly, in non-strict mode,
thispoints towindow;p1.constructorpoints toPersonfunction, when callingp1.constructor();,Personis called as an attribute ofp1, sothispoints top1; when callingvar p2 = p1.constructor;p2( );, it is actually equivalent to callingPerson();directly, sothispoints towindow.