我正在使用history.js。在pushState函数的stateObj中,我想添加对函数的引用(Car.init()Boat.init()。在C ++中,我相信可以使用函数指针。

然后在window.onpopstate上,我想引用该函数并调用它。我可以读取字符串(Car.init(),但是该如何调用该函数呢?我不想使用eval

最佳答案

您可能不应该这样做,但是如果您确实想基于全局点路径名称调用函数,则可以这样完成:



function callFunction(name, var_args) {
  // break the string into individual property/method names
  var parts = name.split('.');

  // start with a reference to the global object
  var target = window;
  var previousTarget = null;

  for (var i = 0; i < parts.length; i++) {
    // keep a copy of the previous reference to use as the `this` value
    previousTarget = target;

    // change the reference to the next named property
    target = target[parts[i]];
  }

  // grab the remaining arguments
  var args = Array.prototype.slice.call(arguments, 1);

  // call the target function, with previousTarget as the subject, using args
  return target.apply(previousTarget, args);
}

// This is in the top-level/global scope. This won't work for a local definition.
var MyApp = {
  currentUser: {
    name: 'Joe',
    displayName: function(greeting) {
      alert(greeting + " ," + this.name + "!");
    }
  },
  openBar: function() {
    alert("The Foo Bar is now open for business!");
  }
};

var functionName = 'MyApp.currentUser.displayName';
callFunction(functionName, "Hello");





这比使用eval更安全(最好避免使用它),但是仍然很古怪,并且JavaScript解释器很难优化。相反,推荐的方法是使用对该函数的引用(指针)。这可能类似于您在C ++中所做的。如果函数不使用this(即,如果它是静态函数,而不是方法),则可以直接引用该函数。

var open = MyApp.openBar;
open();


如果它确实具有this值,则需要使用.bind()方法来保持其与附加对象的关联。

var display = MyApp.currentUser.displayName.bind(MyApp.currentUser);
display("Greetings");


如果将其他参数传递给.bind(),则还可以指定将用于调用该函数的前导参数。

var displayHello = MyApp.currentUser.displayName.bind(MyApp.currentUser, "Hello");
displayHello();

关于javascript - 对象文字的调用函数,以字符串表示-JavaScript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35641042/

10-11 22:12
查看更多