javascript - Answer: When the instance object calls the constructor, what is the point of this in the constructor?
ringa_lee
ringa_lee 2017-07-05 10:39:35
0
1
671

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?

ringa_lee
ringa_lee

ringa_lee

reply all(1)
某草草

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!