JavaScript原型继承的小例子,可以对比一下和Java的继承体系的区别,其实这是编程语言设计的理念不同。
<script>
// 父类 Animal
var Animal = function() {
this.name = 'animal';
};
Animal.prototype = {
run: function() {
console.log(this.name + " run....");
},
eat: function() {
console.log(this.name + " eat...");
}
}
var Dog = function() {
Animal.call(this);
name = 'dog';
this.name = name;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// 覆盖
Dog.prototype.run = function() {
console.log(this.name + "...run...run...");
}
// test
var animal = new Animal();
animal.eat(); // animal eat...
var dog = new Dog();
dog.eat(); // dog eat...
dog.run(); // dog...run...run...
</script>