<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.jb51.net/" />
<title>5种JS继承方法</title>
<script type="text/javascript">
//1、原型链继承
function superType(){
this.property = true;
}
superType.prototype.getSuperValue = function(){
return this.property;
};
function subType(){
this.subProperty = false;
}
subType.prototype = new superType();
subType.prototype.getSubValue = function(){
return this.subProperty;
};
var intance = new subType();
alert(intance.getSubValue());
//2、借用构造函数继承
function superType(){
this.colors = ["red", "blue", "gray"];
}
function subType(){
superType.call(this);
}
var intance1 = new subType();
intance1.colors.push("green");
alert(intance1.colors);
var intance2 = new subType();
alert(intance2.colors);
//3、组合继承(原型链+借用构造函数)
function superType(){
this.name = name;
this.colors = ["red", "blak", "blue"];
}
superType.prototype.sayName = function(){
alert(this.name);
};
function subType(name, age){
superType.call(this, name);
this.age = age;
}
subType.prototype = new superType();
subType.prototype.sayAge = function(){
alert(this.age);
}
var intance1 = new subType("nicholas",23);
intance1.colors.push("green");
alert(intance1.colors);
intance1.sayName();
intance1.sayAge();
//4、寄生式继承
function object(o){
function F(){}
F.prototype = o;
return new F();
}
function createAnother(original){
var clone = object(original);
clone.sayHi = function(){
alert("hi");
};
return clone;
}
var person = {
name : "nicholas",
friends : ["Sheby", "Court", "van"]
};
var anotherPerson = createAnother(person);
anotherPerson.sayHi(); // hi
//5、寄生组合继承
function object(o){
function F(){}
F.prototype = o;
return new F();
}
function inheritPrototype(subType, superType){
var prototype = object(superType.prototype); //create object
prototype.constructor = subType; //augment object
subType.prototype = prototype; //assign object
}
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(name, age){
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function(){
alert(this.age);
};
var instance1 = new SubType("Nicholas", 29);
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
instance1.sayName(); //"Nicholas";
instance1.sayAge(); //29
var instance2 = new SubType("Greg", 27);
alert(instance2.colors); //"red,blue,green"
instance2.sayName(); //"Greg";
instance2.sayAge(); //27
</script>
</head>
<body>
</body>
</html>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。