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,
this
points to the object;When the function is called directly, in non-strict mode,
this
points towindow
;p1.constructor
points toPerson
function, when callingp1.constructor();
,Person
is called as an attribute ofp1
, sothis
points top1
; when callingvar p2 = p1.constructor;p2( );
, it is actually equivalent to callingPerson();
directly, sothis
points towindow
.