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?
这个和
constructor()
方法的内部实现没有什么关系,其实就是函数内this指向的问题。当函数作为对象的属性调用的时候,
this
指向这个对象;当函数直接调用的时候,在非严格模式下,
this
指向window
;p1.constructor
指向的就是Person
函数,当调用p1.constructor();
时,Person
是作为p1
的属性调用的,所以this
指向p1
;当调用var p2 = p1.constructor;p2();
时,其实就相当于直接调用Person();
,所以this
指向window
。