鍍金池/ 問答/Java  網(wǎng)絡安全  HTML/ js中構(gòu)造函數(shù)使用new創(chuàng)建對象時,this與新建對象關系是怎樣的?

js中構(gòu)造函數(shù)使用new創(chuàng)建對象時,this與新建對象關系是怎樣的?

JavaScript高級程序設計(第3版)P144
其中(2)所表達的意思。與我的理解有所出入。
-------------------------------引用高程內(nèi)容 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:(將構(gòu)造函數(shù)的this的值賦給新的對象)
  3. Execute the code inside the constructor (adds properties to the new object).
  4. Return the new object.

------------------------------引用高程內(nèi)容 end--------------------------------------
關于使用new關鍵字調(diào)用構(gòu)造函數(shù)的步驟,以下是我的理解。
(1).var newobj = {}; //首先創(chuàng)建一個新的臨時對象
(2).newobj.call(newobj ); //在新對象的作用域中執(zhí)行構(gòu)造函數(shù)。
也就是將newobj賦給this。而書上說的正相反?!皩?gòu)造函數(shù)的this的值賦給新的對象”。如何理解這句話?

回答
編輯回答
陌南塵

js執(zhí)行的過程中,又不是所有的代碼都是js實現(xiàn)的,書上講的是底層實現(xiàn)。
你現(xiàn)在把new的過程用call解釋了,那你用什么js代碼去解釋call的實現(xiàn)呢?


(1)在內(nèi)存中開辟了一塊區(qū)域。
(2)this指向這塊區(qū)域地址。
(3)操作這個區(qū)域。
(4)返回這個區(qū)域地址。

2017年11月8日 19:16
編輯回答
胭脂淚

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是在運行時動態(tài)賦值的,
也就是說運行時this的值,就是obj的值,非運行時this是沒有分配內(nèi)存的,就談不上誰賦給誰了

2018年1月6日 18:59