zoukankan      html  css  js  c++  java
  • 精通JavaScript第二章——可复用的代码

    我们应该把原型链看做一种委托关系而非类的父子关系,A继承与B,A没有的属性委托给B。原型链就是一种委托机制,允许我们将行为委托给链上更远的一环来处理

    var person = {
      name:"john",
      age:"100",
      job:"teacher",
      getAge:function() {return this.age},
      toString:function() {console.log(this.name + this.age + this.job)},
      extend:function(config) {
        var tmp = Object.create(this);
        console.log(tmp)
        console.log(tmp.age)
      }
    }
    
    person.extend()
    结果
    Object {}
    100
    
    var person = {
      name:"john",
      age:"100",
      job:"teacher",
      getAge:function() {return this.age},
      toString:function() {console.log(this.name + this.age + this.job)},
      extend:function(config) {
        var tmp = Object.create(this);
        for (var key in config)  {
          if (config.hasOwnProperty(key)) {
            tmp[key] = config[key]
          }
        }
        return tmp
      }
    }
    
    person.extend({name:"le",age:"101"})
    
    
    
    
    var bob = Person.extend({
     name:"amy",
     age:"200",
     job:"writer",
     male:"man",
     gs:function() {
    
      console.log(this.name + this.age + this.job + this.male)
     }
    
      
    })
    
    var patty = bob.extend({
      firstname:"patie",
      lastname:"hun",
      gender:'female',
    })
    
    console.log(patty.toString())
    

    如果访问已被覆盖的方法会怎样呢?子对象当然可以覆盖父对象的方法,在任何面向对象系统中都可以这么做。但是在大多数面向对象系统中,被覆盖的方法必须通过类似于super的属性或存储器来访问被父方法,也就是说当覆盖某个方法的时候你可以通过特殊的关键字来调用被覆盖的方法。借下来我们来实现一个super

    var person = {
      name:"john",
      age:"100",
      job:"teacher",
      getAge:function() {return this.age},
      toString:function() {console.log(this.name + this.age + this.job)},
      extend:function(config) {
        var tmp = Object.create(this);
        for (var key in config)  {
          if (config.hasOwnProperty(key)) {
            tmp[key] = config[key]
          }
        }
        return tmp
      }
    }
    
    
    var Teacher = person.extend({
        job:"teacher",
        name:"alice",
        subject:'english literature'
        toString:function() {
            var original = person.toString.call(this);
            return original+""+this.subject+'teacher'
        }
    })
    
    var patty = Teacher.extend({
      name:'dhfisfg',
      age:'sdfsf',
      subject:'chemistry',
      gender:'female',
      job:'ooooo'
    ])
    console.log(patty.toString()
    
  • 相关阅读:
    loadrunner实现字符串的替换
    Windows Server 2008 R2 实现多用户同时登陆
    LoadRunner测试场景中添加负载生成器
    loadrunner统计字符串中指定字符出现的次数
    loadrunner怎么将变量保存到参数中
    loadrunner生成随机数
    loadrunner取出字符串的后面几位
    loadrunner参数化excel数据
    LoadRunner常用函数列表
    loadrunner解决在项目中的难点解决
  • 原文地址:https://www.cnblogs.com/Tjinhui/p/7067277.html
Copyright © 2011-2022 走看看