zoukankan      html  css  js  c++  java
  • JavaScript覆盖原型以及更改原型

    覆盖原型

    //囚犯示例
    //1.定义原型对象
    var proto = {
      sentence : 4, //监禁年限
      probation: 2  //缓刑年限
    };
    //2.定义原型对象的构造函数
    var Prisoner = function(name, id) {
      this.name = name;
      this.id = id;
    };
    //3.将构造函数关联到原型
    Prisoner.prototype = proto;
    //4.实例化对象——采用工厂函数实例化对象
    var makePrisoner = function(name, id) {
      //采用工厂函数实力化对象prisoner
      var prisoner = Object.create( proto );
      prisoner.name = name;
      prisoner.id = id;
      return prisoner;
    };
    
    var firstPrisoner = makePrisoner( 'Joe', '12A' );
    
    //firstPrisoner.sentence在firstPrisoner对象找不到sentence属性,
    //所以查找对象的原型并找到了Both of these output 4
    console.log( firstPrisoner.sentence );
    console.log( firstPrisoner.__proto__.sentence );
    //把对象的sentence属性设置为10
    firstPrisoner.sentence = 10;
    //outputs 10
    //确定对象上的属性值已设置为10
    console.log( firstPrisoner.sentence );
    //但是对象的原型并没有变化,值仍然为4
    console.log( firstPrisoner.__proto__.sentence );
    //为了使获取到的属性回到原型的值,将属性从对象上删除
    delete firstPrisoner.sentence;
    //接下来,JavaScript引擎在对象上不能再找到该属性,
    //必须回头去查找原型链,并在原型对象上找到该属性
    // Both of these output 4
    console.log( firstPrisoner.sentence );
    console.log( firstPrisoner.__proto__.sentence );
    

     ubuntu 终端node输出

    xxh@xxh-E440:~/workspace$ node t6
    4
    4
    10
    4
    4
    4
    

     那么如果改变了原型对象的属性值,会发生什么呢?我知道你在思考。

    见下一节




  • 相关阅读:
    hiho 103 平衡树·Treap
    HDU 5738 Eureka
    codeforces 682D Alyona and Strings
    Photoshop cs5 永久序列号
    httpd.exe你的电脑中缺失msvcr110.dll怎么办
    Gzip压缩启用图文方法详细说明
    帝国CMS开启全站搜索功能
    怎么给电脑统一设置查看文件为列表形式?
    帝国CMS网站地图sitemap的制作教程,分享2种帝国cms网站地图模板
    lol安装包打开没反应
  • 原文地址:https://www.cnblogs.com/nodejsxxh/p/4420585.html
Copyright © 2011-2022 走看看