我有一个问题,我想在javascript中创建一个“hook”,所以我写了一个小函数来实现。
以下是我的代码:
GoogleMaps.prototype.callUserFunc = function( func, args ){
eval('GoogleMaps.' + func + '.apply(func, args)');
}
我的问题是我真的不想使用eval()函数,有更好的方法吗?
对于这个初学者问题,我很抱歉,我的JavaScript水平还有待提高。
谢谢!
我有一个问题,我想在javascript中创建一个“hook”,所以我写了一个小函数来实现。
以下是我的代码:
GoogleMaps.prototype.callUserFunc = function( func, args ){
eval('GoogleMaps.' + func + '.apply(func, args)');
}
我的问题是我真的不想使用eval()函数,有更好的方法吗?
对于这个初学者问题,我很抱歉,我的JavaScript水平还有待提高。
谢谢!
var x = {
someProperty: 5
};
console.log(x["someProperty"]); // => 5
console.log(x.someProperty); // => 5
var y = 'someProperty';
console.log(x[y]); // => 5
x["someProperty"]
与x.someProperty
完全相同。
您可以像这样使用它。
GoogleMaps.prototype.callUserFunc = function( func, args ){
GoogleMaps[func].apply(func, args);
}
apply
中使用 func
没有意义。 - zzzzBovthis
。一开始我把它改成了 this
,但后来又改回来,以保持其与原始代码在功能上的等效性。虽然 func.apply(func, ...
没有太多意义,但他现有的代码可能依赖于这种行为,这是一个不同的讨论。 - Nathan WallGoogleMaps.prototype.callUserFunc = function( func, args ){
GoogleMaps[func].apply(func, args);
//eval('GoogleMaps.' + func + '.apply(func, args)');
}
GoogleMaps
的上下文中调用。GoogleMaps.prototype.callUserFunc = function(func, args) {
return GoogleMaps[func].apply(GoogleMaps, args);
};
GoogleMaps[func](...args...);
GoogleMaps
包含静态可访问的函数,并且没有被用作构造函数来实例化对象。GoogleMaps
的使用方式,那么你的传递函数可能应该在callUserFunc
被调用的对象实例上执行:GoogleMaps.prototype.callUserFunc = function(func, args) {
return this[func].apply(this, args);
};
thisArg
传递给 .apply
。 - I Hate Lazy
func
是在GoogleMaps
对象上还是在.prototype
对象上? - I Hate Lazy