js的原型鏈繼承this、prototype、__proto__、constructor 代碼來(lái)說(shuō)話

純代碼實(shí)現(xiàn)就啰嗦一句,你把它們手打一遍,不理解你打我!

/**
 * 被實(shí)例化對(duì)象
 */
function superClass() {
    var a = 'aa';
    // 通過(guò) this 創(chuàng)建的共有屬性 在被實(shí)例化時(shí)候每個(gè)實(shí)例化對(duì)象都會(huì)創(chuàng)建這個(gè)this的屬性 this相當(dāng)于一個(gè)變量 指向?qū)嵗膶?duì)象,未被實(shí)例化時(shí)指向全局
    this.b = 'bb';
    this.printA = function () {
        console.log(a, 'super printA');
    }
}

// 通過(guò)prototype創(chuàng)建的屬性是原型鏈上的只有本對(duì)象這一份 被實(shí)例化對(duì)象公用
superClass.prototype.printB = function () {
    console.log(this.b , 'super printB')
}

/**
 * 實(shí)例化對(duì)象
 */
var subClass = new superClass();
console.log(superClass.prototype.constructor, 'superClass prototype constructor'); // superClass 
console.log(subClass.__proto__.constructor, 'subClass __proto__ constructor');     // superClass 

// 實(shí)例化對(duì)象的__proto__ 指向被實(shí)例化對(duì)象的原型prototype,對(duì)象的原型的construct指向?qū)ο笞约?console.log(subClass.__proto__ === superClass.prototype); // true
console.log(superClass.prototype.constructor === superClass); // true

// 總結(jié):
// 1、this 和 prototype的區(qū)別就是 當(dāng)實(shí)例化對(duì)象自身需要這個(gè)屬性時(shí)用被實(shí)例化對(duì)象的屬性this,
// 當(dāng)公用一個(gè)被實(shí)例化對(duì)象的屬性時(shí),被實(shí)例化對(duì)象的屬性用 prototype。
// 2、原型鏈指向
// subClass.__proto__ => superClass.prototype
// superClass.prototype.constructor => superClass

最后編輯于
?著作權(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)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,812評(píng)論 25 709
  • 用兩張圖告訴你,為什么你的 App 會(huì)卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 13,918評(píng)論 2 59
  • 猶豫,這個(gè)詞太適合形容曾經(jīng)的我,抉擇不了,不敢行動(dòng),一拖再拖之后也就不了了之,只是在事后,內(nèi)心深處會(huì)隱隱作痛。 錯(cuò)...
    tiffanybly閱讀 639評(píng)論 0 2
  • 在學(xué)習(xí) Swift 時(shí),想改變一下UIAlertController的顯示效果,網(wǎng)上已經(jīng)有許多熱心網(wǎng)友分享的如何自...
    鑫龍魂閱讀 3,006評(píng)論 1 1

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