在子类中继承超类属性

时间:2015-09-03 01:38:16

标签: 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)

JavaScript中有3种可能的继承。

1)Pseudo Classical:

/**
 * Create a new constructor function, whose prototype is the parent   object's prototype.
 * Set the child's prototype to the newly created constructor function.
 **/

var extendObj = function (childObj, parentObj) {
    var tmpObj = function () {}
    tmpObj.prototype = parentObj.prototype;
    childObj.prototype = new tmpObj();
    childObj.prototype.constructor = childObj;
};

https://jsfiddle.net/nikdtu/4wzuwhqw/

2)功能(https://jsfiddle.net/nikdtu/eh7u4pxd/

3)Prototypal(Object.create)(https://jsfiddle.net/nikdtu/dnjkx8w1/

答案 1 :(得分:0)

我希望这能解决你的问题。有关更多继承疑问请遵循eric elliot Prototype Inheritance vs classical inheritance

var str = 'aadbbbcddddkkkkkffffff'
var res = '';
var howMany = 1;
for (var i = 0; i < str.length; i++) {
  if (str[i] == str[i+1]) {
    howMany++;
  } else {
    res += (howMany > 1) ? howMany+str[i] : str[i];
    howMany = 1;
  }
}
console.log(res); //2ad3bc4d5k6f