【问题标题】:Extend prototype with another prototype用另一个原型扩展原型
【发布时间】:2014-03-20 19:33:55
【问题描述】:

如何用原型 B 扩展原型 A,所以每当我调用原型 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,或者只是香草。

【问题讨论】:

  • 为什么不将some.anything(); 添加到resize 事件处理程序中?
  • 你应该更简洁地说明你想要什么。当help.resizer()被调用时,你希望anything()在哪个元素上被执行?在some?但总是,或者只有当调用者是help时?
  • 类似这样的东西 -> jsfiddle.net/6fsub/1 ???
  • 我不希望 some.anything() 出现在 resize 事件中,因为 some.anything() 不会一直运行,只有当我选择将其扩展到 resize 事件时。它应该只在调用者有帮助时运行

标签: javascript prototype extend


【解决方案1】:

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

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();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多