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
753

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?

ringa_lee
ringa_lee

ringa_lee

reply all (1)
某草草

This has nothing to do with the internal implementation of theconstructor()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.

    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!