如果回调功能是对同一个对象的调用,我正在尝试合并检查。
我为我的朋友做了一个粗略的草图(因为他不是JS),他很好地理解了。
function foo(callback){
if(callback === foo) callback.call();
}
foo(function(){
foo()
});
所以我将检查给定prarmeters中的回调是否是相同的函数(自执行?)。
在第一个实例中,我想我可以检查被调用的Function是否是Object的一个实例。因为我正在使用Object构造函数。 (if( newfoo instanceof foo )
)但事实证明,被调用的函数是 IIFE ,并且回调的类型是函数而不是对象。
我编写了一个Javascript示例,很好地涵盖了我的情况。
(function(){
foo = function(){
// Here are Private Functions within this Object
return{
bar: function(callback){
if(typeof callback !== "undefined" && typeof callback === "function") callback(); // && if callback === object constructor
}
}
}
}(this));
var Foo = new foo();
Foo.bar(function(){
Foo.bar(function(){ // This Callbacks should be executed
alert('Callback got called!'); // But the Callback that is no instance of 'Foo' should not be executed!
});
})
我希望我已经解释得足够好了。 希望有人可以帮助我。
谢谢!
答案 0 :(得分:1)
你正试图解决一个非常奇怪的问题,但它仍然可以使它工作。从技术上讲,您只想调用那些在任何地方进行Foo.bar
调用的回调。在这种情况下,您可以使用toString()
方法获取函数代码,并使用正则表达式进行简单检查。像这样:
(function () {
function hasOwnFunction(callback) {
return /\.bar\(/.test(callback.toString());
}
this.foo = function () {
// Here are Private Functions within this Object
return {
bar: function (callback) {
if (typeof callback === "function" && hasOwnFunction(callback)) callback();
}
}
}
}(this));
var Foo = new foo();
Foo.bar(function () {
alert('I should be called 1');
Foo.bar(function () {
alert('I should be called 2')
Foo.bar(function () {
alert('Should not be called');
})
});
});
另请注意,回调成为Foo
的实例的唯一方法是情况Foo.bar(Foo.bar)
。只有这样才能比较callback === this.bar
。然而,这不是你想要的,因为它会导致无限递归。