gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:03:05 24 4
gpt4 key购买 nike

我怎样才能用原型(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,或者只是 Vanilla 。

最佳答案

我不太明白你的问题,因为原型(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com