我想在新的运行之前或之后做一些事情。
function F() {
this.init = function () { alert(0) }
}
F.prototype.init = function () { alert(1) }
new F().init(); // Will not run mine, because on new F(), init is reassigned within the class.
我知道我可以创建自己的方法函数Create(){new F()。init()}
但我想知道是否有办法加入新函数调用?
我希望你理解我的意思。
答案 0 :(得分:1)
new
不是函数调用,F()
是。您可以执行此类操作,将F
替换为您自己的代理。
function F() {
this.init = function () { alert(0) }
}
var oldF = F;
F = function() {
oldF.apply(this, arguments);
this.init = function() { alert(1); };
};
new F().init();
如果你想要一个实用功能来做这件事:
function wrap(constructor, config) {
return function() {
constructor.apply(this, arguments);
for (var key in config) {
this[key] = config[key];
}
}
}
F = wrap(F, {init: function() { alert(1); }});
或使用提供此功能的许多框架/库(ExtJS,jQuery,Prototype)之一。
这可以让你开始尝试做什么,但我不保证它适用于所有情况或实现(仅在V8上测试)。您可以传递F存在的上下文作为附加参数,或者确保对其应用/ bind / call extend
。
function extend(constructor, config) {
this[constructor.name] = function() {
constructor.apply(this, arguments);
for (var key in config) {
this[key] = config[key];
}
}
}
extend(F, {init: function() { alert(1); }});
答案 1 :(得分:0)
javascript中的构造函数就像任何其他方法一样,你真正需要的是javascript中的AOP。
有关javascript的一些优秀AOP库,请参阅this SO question。