首页 > 代码库 > js的继承实现方式
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的继承实现方式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。