使用简洁的原型赋值语法进行Javascript继承

时间:2013-11-27 00:21:53

标签: javascript oop inheritance

我使用这种(prototype)方法定义了两个javascript类:

function Parent () {
    this.a = 1;
}

Parent.prototype = {
    hello : function () {
        return "Hello I'm Parent!";
    },
    setA : function (a) {
        this.a = a;
    }
};

function Child () {
    this.b = 2;
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

Child.prototype = {
    hello : function () {
        return "Hello I'm Child!";
    },
    setB : function (b) {
        this.b = b;
    }
};

我正在使用这种技术,因为我认为它的标准语法过于冗长和稀疏:

Child.prototype.hello = function () {...};

Child.prototype.setB = function (b) {...};

这里的问题是我覆盖 Child.prototype(继承自Parent)丢失.setA()方法(但正确覆盖 .hello())。

合并两个原型解决方案?怎么样?
这种方法会导致问题吗?

2 个答案:

答案 0 :(得分:1)

  

将两个原型合并为解决方案吗?

  

如何?

只需编写一个在对象文字上运行的循环,并将每个属性合并到原型中。

function inherit(Child, Parent, methods) {
    var p = Child.prototype = Object.create(Parent.prototype);
    p.constructor = Child;
    for (var m in methods)
        p[m] = methods[m];
    return p;
}
function Child () {
    Parent.call(this);
    this.b = 2;
}
inherit(Child, Parent, {
    hello : function () {
        return "Hello I'm Child!";
    },
    setB : function (b) {
        this.b = b;
    }
});

答案 1 :(得分:0)

这是我从pro javascript设计模式中复制的一个例子

function extend (subClass, superClass) {
  var F = function () {};
  F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;

  subClass.superclass = superClass.prototype; 
  if (superClass.prototype.constructor === Object.prototype.constructor) {
    superClass.prototype.constructor = superClass;
  } // end if
} // end extend()

function Person (name) {
  this.name = name;
} // end Person()
Person.prototype.getName = function () {
  return this.name;
}; // end getName()

function Author (name, books) {
  Author.superclass.constructor.call(this, name); 
  this.books = books;
} // end Author()

extend(Author, Person);

Author.prototype.getBooks = function () {
  return this.books;
}; // end getBooks()
Author.prototype.getName = function () {
  var name = Author.superclass.getName.call(this);
  return name + " , author of " + this.getBooks();
}; // end getName()

var a = new Author("xxx", "xxx");
console.log(a.getName()); // xxx , author of xxx

作者列出了实现继承的三种方式:基于类,基于原型和基于扩充。

你可以阅读代码,也许可以阅读这本书..

相关问题