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 - 百度坐标,返回目标附近有哪些坐标2. javascript - 关于jsp中嵌入js代码的问题3. javascript - 有什么兼容性比较好的办法来判断浏览器窗口的类型?4. javascript - 一个JS多元运算符的问题5. javascript - html5多个label中其中一个触发change,如何判断是哪一个出发了change6. javascript - 判断用户网络环境7. clone - git sourceTree克隆仓库时,都不停弹出Password Required弹窗,即时输入正确的git账号密码还是弹出8. python - 怎么通过vpn连内网ftp?9. angular.js - angurlarJS的安卓的微信端中用加载ngCookies会出错的问题10. python 正则表达式提取

网公网安备