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. javascript - vue2.0中使用vue2-dropzone的demo,vue2-dropzone的github网址是什么??百度不到。2. vue计算属性怎么样与for结合使用3. html5 - chrome上的video控制条不同4. Java 8:lambda表达式中的强制检查异常处理。为什么是强制性的而不是可选性的?5. javascript - node.js i/o优化6. css3 - 怎样实现手机端高度自适应??(内容有点多)并且消除垂直方向的滚动条7. wordpress - nginx 反代 Varnish 走 Https ,WP后台 ‘您没有足够的权限访问该页面。’8. angular.js - vue/react 渲染内容抖动9. PHP能实现百度网盘的自动化么?10. node.js - version3的generic-pool问题
