javascript - 为什么newtoy.constructor === Gadget在控制台的结果是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
上述例子摘自《面向对象编程指南》一书
问题解答
回答1:如果代码没写错的话,那么就是false,因为你已经把Gadget的原型对象给重写了,而你重写的原型对象中没有constructor属性,可以参考一下《JavaScript高级程序设计》中第六章关于原型的介绍
回答2:楼上正解,Gadget.prototype 被重写了。因为原型对象中有个隐式的constructor,指向了构造函数本身。如下:
原型拓展,最好写成这种形式:
Test.prototype.newFn = function() { ...}
或者使用Object.assign()合并对象:
Test.prototype = Object.assign(Test.prototype, { newAttr: ’’, newFn: function() {... }})
相关文章:
1. docker网络端口映射,没有方便点的操作方法么?2. 为什么我ping不通我的docker容器呢???3. angular.js - angular内容过长展开收起效果4. docker不显示端口映射呢?5. nignx - docker内nginx 80端口被占用6. docker绑定了nginx端口 外部访问不到7. dockerfile - 我用docker build的时候出现下边问题 麻烦帮我看一下8. docker api 开发的端口怎么获取?9. debian - docker依赖的aufs-tools源码哪里可以找到啊?10. docker - 各位电脑上有多少个容器啊?容器一多,自己都搞混了,咋办呢?
