精通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()

转载于:https://www.cnblogs.com/Tjinhui/p/7067277.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值