JavaScript由于没有方法签名,所以只支持实现继承。
JavaScript中实现继承的方法
原型链
JavaScript实现继承的方式是用原型链来实现的。由于每个构造函数都一个属性,指向一个原型对象,所以我们将原型对象等于另一个类型的实例,显然这时这个实例中有一个指向另一个原型的指针。如果这样一层一层的嵌套下去,就构成一个原型链。
function Super() {
this.property = true;
}
Super.prototype.getSuperValue = function() {
return this.property;
}
function Sub {
this.subProperty = false;
}
//Sub 继承 Super
Sub.prototype = new Super();
Sub.prototype.getSubValue() {
return this.subProperty;
}
var instance = new Sub();
alert(instance.getSuperValue()); //true借用构造函数
function Super() {
this.colors = ["red", "blue", "green"];
}
function Sub {
//继承Super
Super.call(this);
}
var instance1 = new Sub();
instance1.colors.push("black");
alert(instance1.colors); //red,blue,green,balck
var instance2 = new Sub();
alert(instance2.colors); //red,blue,green通过call方法,我们在Sub的执行环境下调用了Super的构造函数,使得每个Sub实例都有一个属于自己的colors。而且使用call方法还可以像父类构造函数传参。
组合继承
组合继承是指将原型链和借用构造函数的技术组合到一起。使用原型链来实习对方法和共享属性的继承,使用借用函数来实现对实例属性的继承。
function SuperType(name,age){
this.name = name;
this.age = age;
this.f = [1,2,3,4]
}
SuperType.prototype.sayName = function() {
console.log(this.name)
}
function SubType(name,age) {
SuperType.call(this,name,age)//继承SuperType,并传递参数
this.job = 'actor'
}
SubType.prototype=new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayHello=function() {
console.log('hello')
}
var h = new SubType('hua', 18);
h.sayName()//haha
h.f.push(5)
console.log(h.f)//1,2,3,4,5
var n = new SubType();
console.log(n.f)//1,2,3,4组合继承是JavaScript中最常用的继承模式。
寄生式继承
创建一个仅用来实现继承过程的函数,并在函数内部扩展对象,再将对象返回
此时父类的引用类型属性依然是被所有实例共享
function anotherFunction(original) {
var clone = Object(original);
clone.sayHi = function() {
console.log('hi')
}
return clone;
}
var person = {
name:'lili',
age:'21',
f: [1,2,3]
}
var people1 = anotherFunction(person);
people1.f.push(4)
console.log(people1.f);// 1,2,3,4
var people2 = anotherFunction(person);
console.log(people2.f);// 1,2,3,4 






网友评论文明上网理性发言 已有0人参与
发表评论: