您的位置:首页 > Web前端 > JavaScript

[笔记]javascript面向对象 - 继承的几种模式

2014-08-05 01:29 507 查看
1.继承模式1

继承的本质即将子类的prototype指向父类即可。

function subType() {
if (!arguments.callee.prototype.subSay) {
arguments.callee.prototype.say = function () {
alert('sub_hello_' + this.name);
}
}
this.name = 'aa';
}

function superType() {
if (!arguments.callee.prototype.superSay) {
arguments.callee.prototype.superSay = function () {
alert('super_hello_' + this.name);
}
}
this.name = 'bb';
this.color = ['red', 'black'];
}

subType.prototype = new superType(); //改写了指向,之前的所有原型成员无法继续引用

var t1 = new subType();
//t1.subSay();//报错,无subSay方法
t1.superSay(); //super_hello_aa  实例属性屏蔽了原型属性
var t2 = new subType();
t2.color.push('orange');
alert(t2.color); //red,black,orange
alert(t1.color); //red,black,orange 此时color是subType的原型属性,所以值的改动会影响到所有实例
优点:可以引用父类superType的所有实例成员与原型成员。

缺点:当父类superType的实例属性为引用类型时,如superType.color,任意子类的实例对其值的改动都会影响到所有实例。

2.继承模式2

在1的基础上,利用构造函数将父类的实例属性添加到子类中

function subType(name, age) {
superType.apply(this, arguments);
this.name = name;
}

function superType(name, age) {
if (!arguments.callee.prototype.superSay) {
arguments.callee.prototype.superSay = function () {
alert('super_hello_' + this.name);
}
}
this.name = 'bb';
this.color = ['white', 'black'];
}

subType.prototype = new superType();

var t1 = new subType();
var t2 = new subType();
t2.color.push('orange');
alert(t2.color); //red,black,orange
alert(t1.color); //red,black 实为子类的实例属性
优点:在子类的构造函数中调用父类的构造函数,将父类的实例属性创建到子类中,在最终引用时实际是引用子类的实例属性,避免了1的问题。

缺点:在使用原型继承时:subType.prototype  = new superType()这个过程中实际上又将父类的实例属性添加到了子类的prototype原型对象中,造成了不必要的资源浪费。

3.继承模式3

使用构造函数继承父类的实例属性,使用子类的原型继承父类的原型

function subType(name, age) {
superType.apply(this, arguments);
this.name = name;
}

function superType(name, age) {
if (!arguments.callee.prototype.superSay) {
arguments.callee.prototype.superSay = function () {
alert('super_hello_' + this.name);
}
}
this.name = 'bb';
this.color = ['white', 'black'];
}

//创建一个指定对象的子类实例,该实例的原型指向父类
function createSubType(superType) {
var subType = function () { };
subType.prototype = superType;
return new subType();
}

//实现原型继承
function inheritPrototype(subType, superType) {
var prototype = createSubType(subType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}

inheritPrototype(subType, superType);

var t1 = new subType();
var t2 = new subType();
t2.color.push('orange');
alert(t2.color); //red,black,orange
alert(t1.color); //red,black
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐