猿问

js中构造函数使用new创建对象时,this与新建对象关系是怎样的?

JavaScript高级程序设计(第3版)P144
其中(2)所表达的意思。与我的理解有所出入。
-------------------------------引用高程内容 start---------------------------------------

英文解释
To create a new instance of Person, use the new operator. Calling a constructor in this manner
essentially causes the following four steps to be taken:

  1. Create a new object.

  2. Assign the this value of the constructor to the new object (so this points to the new object).
    PS:(将构造函数的this的值赋给新的对象)

  3. Execute the code inside the constructor (adds properties to the new object).

  4. Return the new object.

------------------------------引用高程内容 end--------------------------------------
关于使用new关键字调用构造函数的步骤,以下是我的理解。
(1).var newobj = {}; //首先创建一个新的临时对象
(2).newobj.call(newobj ); //在新对象的作用域中执行构造函数。
也就是将newobj赋给this。而书上说的正相反。“将构造函数的this的值赋给新的对象”。如何理解这句话?

用call解释第二行其实不妥。但call的功能的过程与我想表达的就是过程一致。
call显示的表达了调用函数的对象。这在我看来就是在设定函数中this的值。也就是this = newobj 
就像您举的例子。this 一定指向新对象的。
所以this与新对象的关系只能是 "this = 新对象" ;而不是"this = 新对象"。这点是否正确?


慕的地3313710
浏览 1065回答 1
1回答

cxxyjsj

this就是指向这个新创建对象的引用而已
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答