行为委托
依靠 Object.create() 去实现 对象之间的委托。
委托对象之间的关系更像是 兄弟 关系,通过 [[Prototype]] 去实现对象的关联。
var Person = {
init: function(name) {
this.name = name;
this.age = 1;
},
getName: function() {
return this.name
},
getAge: function() {
return this.age
},
grow: function() {
this.age ++;
console.log(`${this.name} 又长大了一岁啦!`)
return this.age;
},
cry: function() {
return '呜呜呜...'
}
}
var Child = Object.create(Person);
Child.hungry = function() {
console.log(this.cry() + ' ' + this.name + " is hungry")
}
Child.introduce = function() {
console.log(`I'm ${this.name}, and now I'm ${this.age} years old`);
}
var Ming = Object.create(Child);
Ming.init('小明');
Ming.introduce(); // I'm 小明, and now I'm 1 years old
Ming.hungry(); // 呜呜呜... 小明 is hungry
Ming.grow(); // 小明 又长大了一岁啦!
var Jun = Object.create(Child);
Jun.init('小军');
Jun.introduce(); // I'm 小军, and now I'm 1 years old
Jun.grow(); // 小军 又长大了一岁啦!
Jun.grow(); // 小军 又长大了一岁啦!
Jun.grow(); // 小军 又长大了一岁啦!
Jun.grow(); // 小军 又长大了一岁啦!
Jun.introduce(); // I'm 小军, and now I'm 5 years old
Ming.introduce(); // I'm 小明, and now I'm 2 years old