new 運(yùn)算符實(shí)現(xiàn)細(xì)節(jié)

function Person(name) {
    this.name = name;
}
Person.prototype.getName = function() {
    return this.name
}
var a = new Psrson('sven')
console.log(a.name)  // 'sven'
console.log(a.getName())  //  'sven'
console.log(Object.getPrototypeOf(a) === Person.prototype)  // true
console.log(a)

由上面這個(gè)例子可以知道new在執(zhí)行時(shí)做了哪些事情:

  • 創(chuàng)建一個(gè)新對(duì)象
  • 將傳入的參數(shù)變?yōu)榱诵聦?duì)象的屬性,這是構(gòu)造函數(shù)內(nèi)部的具體實(shí)現(xiàn)決定的
  • 讓新對(duì)象的原型指向構(gòu)造函數(shù)的prototype屬性(構(gòu)造函數(shù)的prototype的constructor屬性默認(rèn)指向構(gòu)造函數(shù)本身)
  • 返回一個(gè)對(duì)象
    所以根據(jù)上面這幾條,我們可以模擬一下new的實(shí)現(xiàn)過(guò)程:
  function Person(name) {
    this.name = name;
  }

  Person.prototype.getName = function() {
    return this.name;
  }

  var objectFactory = function() {
    var obj = new Object(),
      Constructor = [].shift.call(arguments);
    obj.__proto__ = Constructor.prototype;
    var ret = Constructor.apply(obj, arguments);
    return typeof ret === 'object' ? ret : obj;
  }
  var a = objectFactory(Person, 'sven')

  console.log(a.name)
  console.log(a.getName())
  console.log(Object.getPrototypeOf(a) === Person.prototype)
console.log(a)

可以看出,上下兩個(gè)并沒(méi)有什么區(qū)別

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容