原型继承javascript
<script type="text/javascript">java
function Father(){}//构造函数数组
//原型属性app
Father.prototype.name = "李四";函数
Father.prototype.age = 24;this
//原型方法prototype
Father.prototype.showName = function(){对象
return this.name;继承
}ip
Father.prototype.showAge = function(){
return this.age;
}
function Son(){}
//原型链继承
//Son.prototype = Father.prototype;
//Son.prototype = new Father();
//遍历父类的原型
for(var i in Father.prototype){
Son.prototype[i] = Father.prototype[i];
}
var son1 = new Son();
alert(son1.showName());
alert(son1.showAge());
</script>
经典继承
<script>
//构造函数
function Father(name,age,money){
//实例属性
this.name = name;
this.age = age;
this.money = money;
//实例方法
this.showName = function(){
return this.name;
}
this.showAge = function(){
return this.age;
}
this.showMoney = function(){
return this.money;
}
}
function Son(name,age,money,sex){
//经典继承、假装继承、冒充继承(call,apply)只能继承实例
//Father.apply(this,arguments);
//Father.call(this,name,age,money);
Father.apply(this,[name,age,money]);
this.sex = sex;
this.showSex = function(){
return this.sex;
}
}
var son1 = new Son("张三",23,20000,"男");
alert(son1.showName());
alert(son1.showAge());
alert(son1.showMoney());
alert(son1.showSex());
</script>
call与aplly的异同:
第一个参数this都同样,指当前对象
第二个参数不同:call的是一个个的参数列表;apply的是一个数组(arguments也能够)