手掌心
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ì)象中的constructor
是Person
本身,但是在后續(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
方法在原型鏈上加的位置不一樣了。
添加回答
舉報(bào)
0/150
提交
取消