js中prototype的陷阱
来源:互联网 发布:javashop4.0源码 编辑:程序博客网 时间:2024/04/26 05:33
<!DOCTYPE html><html><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><title>原型陷阱</title><meta name="description" content=""><meta name="keywords" content=""><style type="text/css"></style></head><body><script type="text/javascript">//当我们对原型对象执行完全替换时,可能会触发原型链中某种异常//prototype.constructor属性是不可靠的function Dog(){this.tail=true;}var benji=new Dog();var rusty=new Dog();Dog.prototype.say=function(){return "Woof!";}benji.say();//Woof!rusty.say();//Woof!benji.constructor===Dog; //truerusty.constructor===Dog; //true//现在,我们用一个自定义的新对象完全覆盖掉原有的原型对象Dog.prototype={paws: 4,hair: true}//事实证明,这会使原有对象不能访问原型的新增属性,它们依然通过那个神秘的链接//与原有属性对象保持联系。typeof benji.paws; //undefinedbenji.say(); //Woof!typeof benji._proto_.say; //functiontypeof benji_proto_.paws; //undefined//而我们之后创建的所有对象使用的都是被更新后的prototype对象var lucy=new Dog();lucy.say(); //TypeError: lucy.say is not a functionlucy.paws; //4//并且新的对象秘密链接_proto_也指向了新的prototype对象typeof lucy._proto_.say; //undefinedtypeof lucy._proto_.paws; //number//但这时候,新对象的constructor属性就不能再保持正确了,原本应该是Dog()的引用// 却指向了Object()lucy.constructor; // function Object(){[native code]}benji.constructor; //function Dog() {this.tail=true;}//当然,我们可以通过重新设置constructor属性来解决上述所有的异常行为:function Dog(){}Dog.prototype={};new Dog().constructor===Dog; //falseDog.prototype.constructor=Dog;new Dog().constructor===Dog; //true//当我们重写某对象的prototype时,需要重置相应的constructor属性</script></body></html>
0 0
- js中prototype的陷阱
- js 中this 的陷阱
- JS中prototype的用法
- JS中prototype的实例
- js中prototype的笔记
- js中prototype的理解
- js中常见的8个陷阱
- js中prototype的一个小例子
- js中prototype的继承和扩展
- 对js中new、prototype的理解
- JS中 prototype 关键字的使用
- 关于js中prototype的理解
- JS中prototype属性的理解
- js中prototype的理解摘录
- 关于JS中prototype的理解
- JS中__proto__与prototype的关系
- js中constructor和prototype的正确理解
- js 中this陷阱
- Leetcode 4 Median of Two Sorted Arrays
- java设计模式之责任链模式
- Android-LayoutInflater
- 采用CLM在ANDROID上实现的人脸匹配
- fork()函数的简单程序
- js中prototype的陷阱
- 20160505交易记录
- @RequestMapping 参数大全
- 重构一个快不可维护的项目
- 关于一个ListView使用多个item布局在优化时出现显示错乱的解决方案
- Memcached 使用中的问题
- delphi中DDE通信技术
- java面试题
- U盘制作ubuntu安装盘后无法格式化处理