Javascript 在执行另一个被调用的函数之前,有没有办法在JS对象中执行一个函数?
我试图调试JS对象中的大量JS代码。这个JS对象中大约有150个函数,通过单独的脚本分别调用 JS对象示例Javascript 在执行另一个被调用的函数之前,有没有办法在JS对象中执行一个函数?,javascript,class,oop,adobe-analytics,Javascript,Class,Oop,Adobe Analytics,我试图调试JS对象中的大量JS代码。这个JS对象中大约有150个函数,通过单独的脚本分别调用 JS对象示例 var OmnitureCall = { reportA: function() { /* random actions */ }, reportB: function() { /* random actions */ } ... }; 其他JS文件调用对象 OmnitureCall.reportA(...); 在
var OmnitureCall = {
reportA: function() {
/* random actions */
},
reportB: function() {
/* random actions */
}
...
};
其他JS文件调用对象
OmnitureCall.reportA(...);
在外部JS文件中的某个地方,当只发生一个reportA时,会发生多个reportA,这就是为什么我想调试主对象,查看何时调用各种report函数,以及在何处触发double事件。但是,到目前为止,我看到的唯一方法是在OmnitureCall对象中有一个main函数,它充当所有调用的“处理程序”,并进行一些基本调试,然后运行所调用的函数
JS对象处理程序示例
var OmnitureCall = {
handler: function(callback) {
console.log('something is called');
if(typeof(callback) === "function") {
callback();
}
},
reportA: function() {
this.handler(function(){
/* random actions */
});
},
reportB: function() {
this.handler(function(){
/* random actions */
});
}
...
};
缺点:
非常感谢。您可以执行类似操作,只需使用处理程序调用函数即可
window.OmnitureCall = {
handler: function(callback) {
console.log('something is called',typeof(this[callback]));
if(typeof(this[callback]) === "function") {
this[callback]();
}
},
reportA: function() {
console.log('reportA fired');
},
reportB: function() {
console.log('reportB fired');
}
};
编辑:在此上下文中使用“this”之前,我没有这样做,没有任何问题是您想要的,但是它们没有得到广泛的实施,因此我现在还不推荐它。但为了未来,这就是它的样子:
// Your original object
var OmnitureCall = {
reportA: function() {
console.log(arguments, 'hello from report A');
},
reportB: function() {
console.log(arguments, 'hello from report B');
}
// ...
};
// Create our proxy
var OmnitureCall = new Proxy(OmnitureCall,
{
// Since we want to see the calls to methods, we'll use get
get: function(proxy, property)
{
// Tell us what we're calling
console.log('calling ' + property);
// Return it if it exists
return proxy[property] || proxy.getItem(property) || undefined;
}
});
// Returns "calling reportA", ["test", "foo"], "hello from report A":
OmnitureCall.reportA('test', 'foo');
// Returns "calling reportB", [["array", "of", "args"]], "hello from report B":
OmnitureCall.reportB(['args', 'is', 'an', 'array']);
虽然Brett的代码应该可以工作,但您需要更改对该对象的所有调用。例如,您不能执行OmnitureCall.reportA()代码>不再。它必须是OmnitureCall.handler('reportA')
。您可能有控制权,也可能没有控制权,或者很难更改所有引用
使用原始处理程序设置,您确实可以使用应用
或调用
传递此
引用:
var OmnitureCall = {
handler: function(callback, args) {
if(typeof(callback) === "function") {
callback.apply(this, args);
}
},
reportA: function() {
this.handler(function(){
console.log(this);
});
},
reportB: function() {
this.handler(function(){
console.log(arguments);
}, arguments);
}
// ...
};
// Outputs Object {handler: function, reportA: function, reportB: function}
OmnitureCall.reportA();
// Outputs "test", ["foo", 1]
OmnitureCall.reportB('test', ['foo', 1]);