在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

JavaScript高級(jí)程序設(shè)計(jì)(第3版)P144
其中(2)所表達(dá)的意思。與我的理解有所出入。
-------------------------------引用高程內(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的值賦給新的對(duì)象)
  3. Execute the code inside the constructor (adds properties to the new object).
  4. Return the new object.

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

回答
編輯回答
陌南塵

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


(1)在內(nèi)存中開(kāi)辟了一塊區(qū)域。
(2)this指向這塊區(qū)域地址。
(3)操作這個(gè)區(qū)域。
(4)返回這個(gè)區(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 ,其實(shí)他們都只是一個(gè)引用,表明他們指向同一個(gè)地方而已
可能你會(huì)想那究竟是哪個(gè)地址覆蓋哪個(gè)地址,其實(shí)不存在這個(gè)情況,因?yàn)閠his是在運(yùn)行時(shí)動(dòng)態(tài)賦值的,
也就是說(shuō)運(yùn)行時(shí)this的值,就是obj的值,非運(yùn)行時(shí)this是沒(méi)有分配內(nèi)存的,就談不上誰(shuí)賦給誰(shuí)了

2018年1月6日 18:59