两个子类继承了超类的属性,并没有丢失范围

时间:2015-09-02 21:23:54

标签: javascript inheritance prototype

为了帮助你,我将通过一个例子说明问题:

var SuperClass = function() {
  this.propertieOfSuperClass = 'A';

  this.init();
};

SuperClass.prototype.init = function() {
 console.log(this.propertieOfSuperClass); // ouput 'A';
};


// Some code here to do the magic for SubClass1
// Some code here to do the magic for SubClass2

SubClass1:

var SubClass1 = function() {
  this.methodOfSubClass1();
};

SubClass1.prototype.methodOfSubClass1 = function() {
  console.log(this.propertieOfSuperClass); // output 'A';
};

SubClass2:

var SubClass2 = function() {
  this.methodOfSubClass2();
};

SubClass2.prototype.methodOfSubClass = function() {
  console.log(this.propertieOfSuperClass); // output 'A';
};

我希望能够拥有这个SuperClass,我设置属性和其他两个子类,我可以访问SuperClass的属性,但不会失去范围。

我试图在我的SuperClass init方法中使用:

SubClass1.call(this);
SubClass2.call(this);

这会使SuperClass的属性可以访问,但SubClass会失去范围,因此我无法调用methodOfSubClass1methodOfSubClass2,因为他们没有&#39 ; t存在于SuperClass

我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

var SuperClass = function() {
  this.propertieOfSuperClass = 'A';
  this.init();
};

SuperClass.prototype.init = function() {
 console.log(this.propertieOfSuperClass); // ouput 'A';
};

var SubClass1 = function() {
  SuperClass.call(this); // Call parent constructor
  this.methodOfSubClass1();
};
SubClass1.prototype = Object.create(SuperClass.prototype); // Inheritance

SubClass1.prototype.methodOfSubClass1 = function() {
  console.log(this.propertieOfSuperClass); // output 'A';
};

var SubClass2 = function() {
  SuperClass.call(this); // Call parent constructor
  this.methodOfSubClass2();
};
SubClass2.prototype = Object.create(SuperClass.prototype); // Inheritance

SubClass2.prototype.methodOfSubClass2 = function() {
  console.log(this.propertieOfSuperClass); // output 'A';
};

答案 1 :(得分:0)

简单做:

var SuperClass = function SuperClass() {
  this.propertieOfSuperClass = 'A';

  this.init();
};

SuperClass.prototype.init = function() {
 console.log(this.propertieOfSuperClass); // ouput 'A';

 SubClass.call(this);
};

它们:

SuperClass.prototype = Object.create(SubClass.prototype);

他们在SubClass中:

var SubClass = function() {
  console.log(this); // output will be the SuperClass

  this.methodOfSubClass();
};

现在重要的部分是:

SubClass.prototype.constructor = SubClass;

SubClass1.prototype.methodOfSubClass = function() {
  console.log(this.propertieOfSuperClass); // output 'A';
};

您可以对SubClass2执行相同的操作。