This problem actually comes from when analyzing the jQuery source code, I saw that var 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?
某草草2017-07-05 10:41:35
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 to window
; p1.constructor
points to Person
function, when calling p1.constructor();
, Person
is called as an attribute of p1
, so this
points to p1
; when calling var p2 = p1.constructor;p2( );
, it is actually equivalent to calling Person();
directly, so this
points to window
.