javascript - 為什么newtoy.constructor === Gadget在控制臺(tái)的結(jié)果是false?
問題描述
function Gadget(name,color){ this.name=name; this.color=color; this.whatAreYou=function(){return ’I am a ’ + this.color + ’ ’ + this.name; };}Gadget.prototype={ price:100, rating:3, getInfo:function(){return ’Rating: ’ + this.rating + ’, price: ’ + this.price; }};var newtoy=new Gadget(’webcam’,’black’);new.rating;//3newtoy.constructor === Gadget;//true
上述例子摘自《面向?qū)ο缶幊讨改稀芬粫?/p>
問題解答
回答1:如果代碼沒寫錯(cuò)的話,那么就是false,因?yàn)槟阋呀?jīng)把Gadget的原型對(duì)象給重寫了,而你重寫的原型對(duì)象中沒有constructor屬性,可以參考一下《JavaScript高級(jí)程序設(shè)計(jì)》中第六章關(guān)于原型的介紹
回答2:樓上正解,Gadget.prototype 被重寫了。因?yàn)樵蛯?duì)象中有個(gè)隱式的constructor,指向了構(gòu)造函數(shù)本身。如下:
原型拓展,最好寫成這種形式:
Test.prototype.newFn = function() { ...}
或者使用Object.assign()合并對(duì)象:
Test.prototype = Object.assign(Test.prototype, { newAttr: ’’, newFn: function() {... }})
相關(guān)文章:
1. docker-compose中volumes的問題2. angular.js - angular內(nèi)容過長(zhǎng)展開收起效果3. dockerfile - [docker build image失敗- npm install]4. golang - 用IDE看docker源碼時(shí)的小問題5. 表單提交驗(yàn)證,沒反應(yīng),求老師指點(diǎn)6. mysql函數(shù)unix_timestamp如何處理1970.1.1以前的數(shù)據(jù)?7. Mac下mysql在控制面板中stop按鈕點(diǎn)了沒反應(yīng)8. 老師,樣式?jīng)]有變呀?9. mysql - 記錄開始時(shí)間和結(jié)束時(shí)間,表字段類型用timestamp還是datetime?10. MySQL 什么需求下(情況下)才使用事務(wù)?

網(wǎng)公網(wǎng)安備