js的继承实现方式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
以上是关于js的继承实现方式的主要内容,如果未能解决你的问题,请参考以下文章