简体   繁体   中英

Javascript Eval code issue

I have an issue, where I want to create a 'hook' in javascript, so I created a small function to do it.

Here is my code:

GoogleMaps.prototype.callUserFunc = function( func, args ){
  eval('GoogleMaps.' + func + '.apply(func, args)');
}

The issue I have is I really don't want to use the eval() function, is there any better way of doing this?

I apologise for the noobish question, my javascript is a little on the poor side.

Thanks!

You can use square bracket notation to access properties of an object.

example:

var x = {
    someProperty: 5
};

console.log(x["someProperty"]); // => 5
console.log(x.someProperty); // => 5

var y = 'someProperty';
console.log(x[y]); // => 5

x["someProperty"] is identical to x.someProperty .

You can use it like this.

GoogleMaps.prototype.callUserFunc = function( func, args ){
  GoogleMaps[func].apply(func, args);
}
GoogleMaps.prototype.callUserFunc = function( func, args ){
  GoogleMaps[func].apply(func, args);
  //eval('GoogleMaps.' + func + '.apply(func, args)');
}

A true passthrough function would return the value that was returned by the function, and would be called in the context of GoogleMaps .

Your primary issue was not knowing that the array-access notation could be used on any object:

GoogleMaps.prototype.callUserFunc = function(func, args) {
    return GoogleMaps[func].apply(GoogleMaps, args);
};

In general, though, you'd probably be better off writing your code as:

GoogleMaps[func](...args...);

But this all assumes that GoogleMaps contains statically accessible functions, and isn't being used as a constructor to instantiate objects.

Without knowing how GoogleMaps is being used, it's possible that your passthrough function should be executing off of the object instance that callUserFunc is being called on:

GoogleMaps.prototype.callUserFunc = function(func, args) {
    return this[func].apply(this, args);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM