javascript - 用另一个原型(prototype)扩展原型(prototype)

标签 javascript prototype extend

如何用原型(prototype) B 扩展原型(prototype) A,这样每当我调用原型(prototype) A 时,两者都会被执行?

var Helper = function() {

}
Helper.prototype.resizer = function() {   
  $('body').append(' Window resized ');
}

var Something = function() {
  // Extend Helper.resizer with Something.anything
  // extend(Helper.resizer, this.anything);
}
Something.prototype.anything = function() {   
  $('body').append(' Run this on resize to ');
}

var help = new Helper();
var some = new Something();

$(window).on("resize", function(){
  help.resizer();
});

在codepen上做了一个例子: http://codepen.io/robbue/pen/892c8f61e1b5a970d6f694a59db401a6 允许使用 jQuery,或者只是普通的。

最佳答案

我不太明白你的问题,因为原型(prototype)没有执行,但我认为你想要这样的东西:

var Helper = function() {}
Helper.prototype.resizer = function() {   
  $('body').append(' Window resized ');
}

var Something = function(h) {
  var oldresizer = h.resizer,
      that = this;
  h.resizer = function() {
      var res = oldresizer.apply(this, arguments);
      that.anything();
      return res;
  };
}
Something.prototype.anything = function() {   
  $('body').append(' Run this on resize to ');
}

var help = new Helper();
new Something(help);

$(window).on("resize", function(){
  help.resizer();
});

或者:

function Helper() {}
Helper.prototype.resizer = function() {   
  $('body').append(' Window resized ');
}

function Something() { // inherits Helper
  Helper.apply(this, arguments);
}
Something.prototype = Object.create(Helper.prototype);
Something.prototype.anything = function() {   
  $('body').append(' Run this on resize to ');
};
Something.prototype.resizer = function() {
  Helper.prototype.resizer.call(this);
  this.anything();
};

var help = new Something(help);

$(window).on("resize", function(){
  help.resizer();
});

关于javascript - 用另一个原型(prototype)扩展原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22530907/

相关文章:

css - Plupload:获取文件输入的id

python - 如何在没有 list.extend 方法和没有 '+' 运算符的情况下扩展列表

jquery - 使用 jQuery.extend 覆盖函数的原因可能是什么?

javascript - 设置 div 背景颜色的 Angular 指令

javascript - d3 在将嵌套数据传递给 d3.stack 时返回错误 `e is not a function`

javascript 原型(prototype)对象 this 值

javascript - 仍然对 js Prototype 感到困惑

javascript - 更简洁地编写 if 语句

javascript - 选择同一类的多个 id

Jquery扩展现有功能