/**
* 继承有两种方式,接口继承和实现继承,
* ECMAScript只支持实现继承,主要依靠原型链来实现
* 原型链:利用原型,让一个引用类型继承另一个引用类型的方法和属性
* 原型链:
* 优点:可以实现原型继承
* 缺点:1、包含引用类型值的原型属性会被所有实例共享,
* 2、创建子类型的实例时,不能向超类型的构造函数传递参数
* 借用构造函数:优点: 1、在子类型的构造函数内部调用超类型的构造函数 apply() call()
* 2、可以向超类型传值
* 缺点:1、方法都在构造函数中定义,函数复用无从谈起,
* 2、在超类型的原型中定义的方法,对子类型不可见
*
* 组合继承:(原型+构造函数) 使用原型链实现对原型属性和方法的继承,通过借用构造函数来实现对实例属性的继承
* 优点: 通过在原型上定义方法实现了函数复用,又能保证每个实例都有它自己的属性
* 避免了原型链和借用构造函数的缺陷,融合优点,是最常用的继承方式。
* 缺点:无论什么情况下都会调用两次超类型构造函数,1、创建子类型原型的时候
* 2、子类型构造函数内部
*
*/
function SuperType(name){
this.colors = ["red","bule","green"];
this.property = true;
this.name = name;
}
SuperType.prototype.getSuperValue = function(){
return this.property;
}
SuperType.prototype.sayName = function(){
console.log(this.name);
}
function SubType(name,age){
this.subproperty = false;
SuperType.call(this,name); //另一种继承方式,构造函数
this.age = age;
}
SubType.prototype = new SuperType(); //继承语法 ,原型继承
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
console.log(this.age);
}
SubType.prototype.getSubValue = function() { //通过原型链实现继承时,不能使用创建字面量创建原型方法,
// 这样做 会重写原型链
return this.subproperty;
}
SubType.prototype.getSuperValue = function(){
return false;
}
var instance1 = new SubType("Tome",21);
console.log(instance1.getSuperValue());
console.log(instance1 instanceof Object);
console.log(instance1 instanceof SuperType);
console.log(instance1 instanceof SubType);
console.log(Object.prototype.isPrototypeOf(instance1));
console.log(SuperType.prototype.isPrototypeOf(instance1));
console.log(SubType.prototype.isPrototypeOf(instance1));
instance1.colors.push("black");
console.log(instance1.colors);
console.log(instance1.name);
console.log(instance1.age);
instance1.sayAge();
instance1.sayName();
var instance2 = new SubType("clos",22); //原型链的第一个问题
console.log(instance2.colors);
console.log(instance2.name);
console.log(instance2.age);
instance2.sayAge();
instance2.sayName();
javascript继承,原型链继承、借用构造函数、组合继承
最新推荐文章于 2024-09-26 11:35:30 发布