js的继承实现方式

1. 使用call或者apply来实现js对象继承

     function Animal(age){
this.age = age;
this.say = function(){
console.log('age:'+this.age);
};
}
function Dog(age,nickname){
Animal.call(this,age);
// Animal.apply(this,[age]);
this.nickname = nickname;
this.say = function(){
console.log('nickname:'+this.nickname+',age:'+this.age);
};
}
var animal = new Animal(11);
var dog = new Dog(12,'dog');
animal.say();
dog.say();

2. 使用原型链来实现js继承;

     function Animal(){}
Animal.prototype.age = 11;
Animal.prototype.say = function(){
console.log('age:'+this.age);
};
function Dog(){}
Dog.prototype = new Animal();
Dog.prototype.nickname = 'dog';
Dog.prototype.say = function(){
console.log('nickname:'+this.nickname+',age:'+this.age);
};
var animal = new Animal();
var dog = new Dog();
animal.say();
dog.say();

3. 使用原型链和apply混合实现。

     function Animal(age){
this.age = age;
}
Animal.prototype.say = function(){
console.log('age:'+this.age);
};
function Dog(age,nickname){
Animal.call(this,age);
// Animal.apply(this,[age]);
this.nickname = nickname;
}
Dog.prototype.say = function(){
console.log('nickname:'+this.nickname+',age:'+this.age);
};
var animal = new Animal(11);
var dog = new Dog(12,'dog');
animal.say();
dog.say();
上一篇:【C#学习笔记】调用C++生成的DLL


下一篇:JS中对象继承方式