ES5继承

原型继承

<script type="text/javascript">

function Father(){}//构造函数

//原型属性

Father.prototype.name = "李四";

Father.prototype.age = 24;

//原型方法

Father.prototype.showName = function(){

return this.name;

}

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也可以)

上一篇:网络编程之基于UDP协议的套接字编程、基于socketserver实现并发的socket


下一篇:Python3实现自动点赞抖音小姐姐