第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

js組合繼承中斧正constructor的指向有什么用。

js組合繼承中斧正constructor的指向有什么用。

手掌心 2018-09-06 09:11:49
Friend.prototype.constructor = Friend 原先Friend.prototype.constructor指向的是Person但是感覺(jué)并沒(méi)有什么用有沒(méi)有彈出的結(jié)果都一樣,感覺(jué)都很好完成了繼承function Person(name,age){            this.name = name;            this.age = age;            if(typeof this.sayName != 'function'){                Person.prototype.sayName = function(){                    alert(this.name);                }            }        }                var per1 = new Person('zhang',23);        var per2 = new Person('wagn',23);                function Friend(name,age,sex){            Person.call(this,name,age);            this.sex = sex;        }             Friend.prototype = new Person();            Friend.prototype.constructor = Friend; //不斧正時(shí),constructor指向Person            Friend.prototype.saySex=function(){                alert(this.sex);            }                var fri1 = new Friend('wang','11','nan');        var fri2 = new Friend('li','55','nv');        alert(Person.prototype.constructor);
查看完整描述

1 回答

?
繁花如伊

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊

用ES6簡(jiǎn)化了下:

    class Person {

    }    class Friend extends Person {

    }
    
    console.log('%O', Person.prototype.constructor); // Person
    console.log('%O', Friend.prototype.constructor); // Friend

ES6中已經(jīng)修復(fù)了這個(gè)constructor,始終指向類(lèi)本身 
用ES5簡(jiǎn)化下:

    function Person() {
    
    }    
    function Friend() {
    
    }
    
    Friend.prototype = new Person();    // Friend.prototype.constructor = Friend;
    console.log('%O', Person.prototype.constructor); // Person
    console.log('%O', Friend.prototype.constructor); // Person

為什么Friend.prototype.constructor也是Person,這里題主是知道的。我還是自己學(xué)習(xí)再次總結(jié)下,因?yàn)閷?shí)例化Person類(lèi)時(shí)返回的對(duì)象中的constructorPerson本身,但是在后續(xù)實(shí)例化等過(guò)程中不會(huì)直接使用到constructor,但是出于對(duì)該函數(shù)本身的含義的理解,于是我們修正了constructor。

constructor 的含義是 返回指向創(chuàng)建了該對(duì)象原型的函數(shù)引用


相關(guān)應(yīng)用例子:

var f = (function() {    function Person() {
    
    }    
    function Friend() {
    
    }
    
    Friend.prototype = new Person();    // Friend.prototype.constructor = Friend;
    return new Friend();
}())// 如果需要擴(kuò)展原型方法f.constructor.prototype.sayHello = function() {    console.log('hello');
}
f.sayHello(); // helloconsole.log(f);

通過(guò)上面的例子可以看出修正了的constructor與沒(méi)有修改的差別是擴(kuò)展的sayHello方法在原型鏈上加的位置不一樣了。


查看完整回答
反對(duì) 回復(fù) 2018-10-27
  • 1 回答
  • 0 關(guān)注
  • 1000 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)