拷贝继承
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>
//继承 : 子类不影响父类,子类可以继承父类的一些功能 ( 代码复用 )
//属性的继承 : 调用父类的构造函数 call
//方法的继承 : for in : 拷贝继承 (jquery也是采用拷贝继承extend)
function CreatePerson(name,sex){ //父类
this.name = name;
this.sex = sex;
}
CreatePerson.prototype.showName = function(){
alert( this.name );
};
var p1 = new CreatePerson('小明','男');
//p1.showName();
function CreateStar(name,sex,job){ //子类
CreatePerson.call(this,name,sex);
this.job = job;
}
//CreateStar.prototype = CreatePerson.prototype;
extend( CreateStar.prototype , CreatePerson.prototype );
CreateStar.prototype.showJob = function(){
};
var p2 = new CreateStar('黄晓明','男','演员');
p2.showName();
function extend(obj1,obj2){
for(var attr in obj2){
obj1[attr] = obj2[attr];
}
}
</script>
</head>
<body>
</body>
</html>
类式继承
<script>
//类 : JS是没有类的概念的 , 把JS中的构造函数看做的类
//要做属性和方法继承的时候,要分开继承
function Aaa() { //父类
this.name = [1, 2, 3];
}
Aaa.prototype.showName = function() {
alert(this.name);
};
function Bbb() { //子类
Aaa.call(this);
}
var F = function() {};
F.prototype = Aaa.prototype;
Bbb.prototype = new F();
Bbb.prototype.constructor = Bbb; //修正指向问题
var b1 = new Bbb();
//b1.showName();
//alert( b1.name );
//alert( b1.constructor );
b1.name.push(4);
var b2 = new Bbb();
alert(b2.name);
</script>
原型继承
var a = {
name: '小明'
};
var b = cloneObj(a);
b.name = '小强';
//alert( b.name );
alert(a.name);
function cloneObj(obj) {
var F = function() {};
F.prototype = obj;
return new F();
}
拷贝继承: 通用型的 有new或无new的时候都可以
类式继承: new构造函数
原型继承: 无new的对象