☊ 【要求】:实现一个Animal类, 和一个继承它的Dog类
☛ 【实现】:
function Animal(name) {
this.name = name;
}
Animal.prototype.cry = function() {
console.log('I am ' + this.name);
}
function Dog(name) {
Animal.call(this, name);
this.hobby = 'running';
}
Dog.prototype = new Animal();
// 注意要放在上条语句的下面
Dog.prototype.run = function() {
console.log('I like ' + this.hobby);
}
var dog = new Dog('doggy');
dog.run(); // 'I like running'
dog.cry(); // 'I am doggy'
☊ 【要求】:用JS实现一个类继承函数
function extend(parent){ /*...*/}
☛ 【实现】:
function Animal(name) {
this.name = name;
}
Animal.prototype.cry = function() {
console.log('I am ' + this.name);
}
var People = {
name: 'bb',
say: function() {
console.log(this.name);
}
}
function extend(parent) {
if (typeof parent == 'function') {
function child() {
parent.call(this, ...arguments);
}
// 可以在 child 的原型上自己定义方法,而不会影响 parent 的原型
child.prototype = new parent();
}
if (typeof parent == 'object') {
function child() {};
// 将 parent 作为 child 的原型
child.prototype = parent;
}
return child;
}
var Pet = extend(Animal);
var dog = new Pet('doggy'); // child {name: "doggy"}
dog.name = 'Doggy';
dog.cry(); // 'I am Doggy'
var Person = extend(People);
var bob = new Person; // child {name: "Bob"}
bob.name = 'Bob';
bob.say(); // 'Bob'