ITeye博客

javascript的继承机制

water84222 · 2012-04-11 17:08 · javascript · Web前端 · Markdown

转载于:http://www.iteye.com/topic/437567

 

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

1.先定义一个父类Person

Js代码   收藏代码

  1. function Person(name, sex) {
  2. this.name = name;
  3. this.sex = sex;
  4. this.move = function() {
  5. alert("move");
  6. };
  7. }

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

 

Js代码   收藏代码

  1. function Man(name, sex, address, phone) {
  2. this.pe = Person;
  3. this.pe(name, sex);
  4. delete this.pe;
  5. this.address = address;
  6. this.phone = phone;
  7. }
  8. function Woman(name, sex, birthday) {
  9. this.pe = Person;
  10. this.pe(name, sex);
  11. delete this.pe;
  12. this.birthday = birthday;
  13. }

 

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

Js代码   收藏代码

  1. function Man2(name, sex, address, phone) {
  2. Person.call(this, name, sex);
  3. this.address = address;
  4. this.phone = phone;
  5. }

 

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

 

Js代码   收藏代码

  1. function Man3(name, sex, address, phone) {
  2. Person.apply(this, new Array(name, sex));
  3. this.address = address;
  4. this.phone = phone;
  5. }

 

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

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

原型prototype链如下:

 

Js代码   收藏代码

  1. function Person2() {
  2. }
  3. Person2.prototype.name = "";
  4. Person2.prototype.sex = "";
  5. Person2.prototype.move = function() {
  6. alert(this.name);
  7. };
  8. function Man4() {
  9. }
  10. 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!");
};

 

Man5.prototype.say();

Man5.prototype.login();

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。