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的值赋给新的对象”。如何理解这句话?

阅读 2.8k
2 个回答

js执行的过程中,又不是所有的代码都是js实现的,书上讲的是底层实现。
你现在把new的过程用call解释了,那你用什么js代码去解释call的实现呢?


(1)在内存中开辟了一块区域。
(2)this指向这块区域地址。
(3)操作这个区域。
(4)返回这个区域地址。

new 操作符可以是这样模拟
function F(){}
function new(){

var obj = Object.create(F.prototype);
var ref = F.apply(obj, arguments);
if(Object(ref) === ref) {
    return ref
} else {
    return obj;
}

}
this 赋给 obj 或者是obj是赋给this ,其实他们都只是一个引用,表明他们指向同一个地方而已
可能你会想那究竟是哪个地址覆盖哪个地址,其实不存在这个情况,因为this是在运行时动态赋值的,
也就是说运行时this的值,就是obj的值,非运行时this是没有分配内存的,就谈不上谁赋给谁了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题