//【原型模式】--重写原型对象prototype的影响 2014-12-12
//定义构造函数
function Person() { }
//直接指定构造函数的原型为一个对象(为了简化逐个给原型添加成员的操作),但是这样写带来了两个问题,我们先来看第一个问题:
Person.prototype = {
    name: "wede",
    age: 29,
    job: "SoftWare",
    say: function () {
        alert("Hello,I'm " + this.name + "," + this.age + " years old,i'm a " + this.job);
    }
};
//看看此时原型对象的constructor
document.write(Person.prototype.constructor + "<br/>"); //function Object() { [native code] }

//是Object
//这就意味着如果此时我们对其进行类型检测就会出问题,不会得到预期的类型Person,因为在上面prototype实际上是被重写了。
var person = new Person();
document.write(person.constructor + "<br/>"); //function Object() { [native code] },其实这里我们期望的是Person
document.write(person instanceof Person); //true

//解决办法:
Person.prototype = {
    constructor: Person, //重新指定其constructor属性
    name: "wede",
    age: 29,
    job: "SoftWare",
    say: function () {
        alert("Hello,I'm " + this.name + "," + this.age + " years old,i'm a " + this.job);
    }
};

//然后我们得到了预期的结果:
document.write(Person.prototype.constructor + "<br/>"); //function Person() { }
document.write(person.constructor + "<br/>"); //function Person() { }
document.write(person instanceof Person); //true

//即使这样,还是会有不足,那就是本来是不可枚举的constructor属性由于重设的缘故导致它的[[Enumerable]]内部特性变为了true,
//也就是说,现在遍历对象会包含constructor属性:
for (var prop in Person.prototype) {
    document.write(prop + ","); //constructor,name,age,job,say,
}
for (var prop in person) {
    document.write(prop + ","); //constructor,name,age,job,say,
}
//这里需要补充说明的是,使用for-in循环时,返回的是所有能够通过对象访问、可枚举的属性,其中既包括存在于实例中的属性,也包括存在于原型中的属性。《高三》P153
//目前只有针对ECMAScript 5的解决方案:即通过Object.definProperty()方法重新设置原型中的constructor属性。《高三》P156

//给prototype直接指定另一个对象带来的第二个问题:
//重写原型对象切断了现有原型与任何之前存在的对象实例之间的联系,因为实例引用的([[Prototype]])最初的原型。
//详见《高三》P156

最新文章

  1. Android开发之Android Material Design Toolbar自定义随笔
  2. 猎奇过后,VR还有什么能让用户买单?
  3. 简直要逆天!超炫的 HTML5 粒子效果进度条
  4. XCode6无论如何都无法升级为XCode8为什么呀?
  5. Node.js-提供了四种形式的定时器
  6. Rails下cloud datastore的使用
  7. Spring(一)简述
  8. spring的框架集,简化的编程模型
  9. 浅谈css中的position属性
  10. 打造无DLL版穿透防火墙Downloader
  11. css.day01
  12. hitTest:withEvent:方法(此方法可实现点击穿透、点击下层视图功能)
  13. HTML中加载flash方法
  14. Spring (三)
  15. 01.阿里云SDK调用,获取ESC主机详细信息
  16. RS232串口的Windows编程纪要
  17. matplot绘图基本使用
  18. springmvc下载文件
  19. selinux开关
  20. 微服务Kong(五)——添加一个用户(Consumer)

热门文章

  1. mysql索引分类
  2. win10系统在执行“ vagrant box add centos7 vagrant-centos-7.box”添加box时,报错“Vagrant failed to initialize at a very early stage: Failed to locate the powershell executable on the available PATH. ”
  3. CentOS7 docker开启tcp端口并进行客户端远程连接
  4. 如何规避同时使用v-if与v-for?
  5. Androidstudio 编译慢 这样的体验肯定很多人都有!!!
  6. Qt编写数据可视化大屏界面电子看板5-恢复布局
  7. spring常用模式--模板模式
  8. golang的下载与安装
  9. 针对thinkphp 5框架存储过程bug而重写的存储过程的扩展类
  10. Python学习笔记——esle和with 语句