JavaScript面向对象(二):继承

来源:互联网 发布:怎么用手机做淘宝客服 编辑:程序博客网 时间:2024/05/18 00:55

JS类的继承

JS类继承的方式有几种,这里讲两种比较简单易懂、有代表性的。


方法1:通过apply

function father(){
this.job = "president";
}


function son(){
father.apply(this,arguments);
this.info = "student";
}


var ss = new son();
document.write(ss.job); //输出president


方法2:通过prototype

function father(){
this.job = "president";
}


function son(){
this.info = "student";
}
son.prototype = new father();
son.prototype.constructor = son;



var ss = new son();
document.write(ss.job);


如果习惯了java,C++中类继承的用法,那方法1容易理解点,也比较直观。


prototype用处

在js中prototype是个不太好理解的概念。关于它的定义是: 返回对象类型原型引用。

它只能在类身上使用,不能在类的实例化对象上使用。你可以简单的理解成,我们通过它能扩展类的功能。

像类的继承中,son.prototype = new father();  可以理解成把father的功能复复制给son了,但这样一来就覆盖掉了son原来的功能,再通过son.prototype.constructor =son把原来的功能找回来。 这样son就同时拥有之前的功能和father的功能,达到了继承的效果。



0 0
原创粉丝点击