方式"/>
JS中实现继承的7中方式
1.原型链继承:将父类的实例作为子类的原型
// 定义一个父类型
function Animal(name) {this.name = name;this.say = function(){ console.info('I am ' + this.name); }
}
// 原型对象方法
Animal.prototype.eat = function(food) {console.info(this.name + '正在吃' + food);
}
// 定义子类
function Cat() {}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
var cat = new Cat();
继承链:
缺点:创建子类实例时,无法向父类构造函数传递参数,。
2.构造函数继承:
// 定义一个父类型
function Animal(name) {this.name = name;this.say = function(){ console.info('I am' + this.name); }
}
// 原型对象方法
Animal.prototype.eat = function(food) {console.info(this.name + '正在吃' + food);
}
// 定义子类
function Cat(name, age) {Animal.call(this, name);this.age = age;
}
var cat = new Cat();
3.实例继承:
// 定义一个父类型
function Animal(name) {this.name = name;this.say = function(){ console.info('I am' + this.name); }
}
// 原型对象方法
Animal.prototype.eat = function(food) {console.info(this.name + '正在吃' + food);
}
// 定义子类
function Cat(name,age) {// 先创建子类实例var o = new Animal(name);o.age = age;return o;
}
var cat = new Cat();
4.拷贝继承: 无法获取父类不可for in遍历的方法
// 定义一个父类型
function Animal (name) {this.name = name;this.say = function(){ console.log(I’m this.name); } }
// 原型对象方法
Animal.prototype.eat = function(food) {console.log(this.name + '吃:' + food);
};
function Cat(name,age){var animal = new Animal(name);for(var p in animal){Cat.prototype[p] = animal[p]; }this.age = age
}
var cat = new Cat();
5. 组合继承:
// 定义一个父类型
function Animal (name) {this.name = name;this.say = function(){ console.log(I’m this.name); } }
// 原型对象方法
Animal.prototype.eat = function(food) {console.log(this.name + '吃:' + food);
};
function Cat(name,age){Animal.call(this,name);this.age = age
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat = new Cat();
6. 寄生组合继承:
// 定义一个父类型
function Animal (name) {this.name = name;this.say = function(){ console.log(I’m this.name); } }
// 原型对象方法
Animal.prototype.eat = function(food) {console.log(this.name + '吃:' + food);
};
function Cat(name,age){ Animal.call(this,name); this.age = age
}
(function(){ // 创建一个没有实例方法的类var Super = function(){};Super.prototype = Animal.prototype; //将实例作为子类的原型 Cat.prototype = new Super();})();var cat = new Cat();
7. ES6 class extends继承:
Class 父类型{ constructor(){
}
... }
更多推荐
JS中实现继承的7中方式
发布评论