论坛首页 Web前端技术论坛

javascript继承

浏览 2287 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (7) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-08-01   最后修改:2009-08-01

测试javascript的继承机制,首先,要理解什么叫继承:继承主要是指子类拥有父类开放的属性及方法,其实javascript是不包含继承这种机制的,但是在现在这个面向对象充斥着开发人员的开发的时候,难免javascript也要模拟这样的一种写吧,尽量满足大部份开发人员的开发习惯,下面请看javascript是如何实现这些继承体系的。

1.先定义一个父类Person

function Person(name, sex) {
    this.name = name;
    this.sex = sex;
    this.move = function() {
        alert("move");
    };
}


2.对象冒充
可以冒充得到正确结果,其实javascript是这样的,将整个方法替换掉pe,当我们调用this.(name,sex);时相当于在Man里面执行上面的那一段代码,而此时的this已经代表的是Man对象,使Man也具有了name,sex等属性与及move方法。

 

function Man(name, sex, address, phone) {
    this.pe = Person;
    this.pe(name, sex);
    delete this.pe;
    this.address = address;
    this.phone = phone;
}

function Woman(name, sex, birthday) {
    this.pe = Person;
    this.pe(name, sex);
    delete this.pe;
    this.birthday = birthday;
}
 

3.call 方法实现继承,call方法里面会将this及Person中的参数传递到调用的方法中,此时的this代表的是Man2对象,当调用到Person的构造方法的时候,调用this.name的时候已经是Man2.name了,这种方法也可以实现继承。

function Man2(name, sex, address, phone) {
    Person.call(this, name, sex);
    this.address = address;
    this.phone = phone;
}

 

4.apply 方法实现继承,其实apply方法和call方法是一样,只不过apply传递过去的参数要用一个数据包装起来而已。

 

function Man3(name, sex, address, phone) {
    Person.apply(this, new Array(name, sex));
    this.address = address;
    this.phone = phone;
}
 

5.若父类中有通过prototype定义的方法或者属性,上述的三种方法无法实现继承。

原型链的缺点是不支持多继承。

原型prototype链如下:

 

function Person2() {

}

Person2.prototype.name = "";
Person2.prototype.sex = "";
Person2.prototype.move = function() {
    alert(this.name);
};

function Man4() {

}

Man4.prototype = new Person2();
 

5.混合方式,通过混合方式,可以达到最大的重用。
function Person3(name, sex) {
    this.name = name;
    this.sex = sex;
}

Person3.prototype.login = function() {
    alert("prototype constructual");
};

function Man5(name, sex, birthday) {
    Person3.call(this, name, sex);
    this.birthday = birthday;
}

Man5.prototype = new Person3();

Man5.prototype.say = function() {
    alert("say hello!");
};

论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics