我们应该把原型链看做一种委托关系而非类的父子关系,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()