0

我应该如何让它工作?

var param = 'someFunction';

require('views/MyView').[param]();

当我运行此代码时,出现以下错误

SyntaxError: missing name after . operator
require('views/MyView').[renderMethod]();
4

1 回答 1

3

. and [] are kind of the same thing.

What you want is require('views/MyView')[renderMethod]();

require(...) will return the exported module, which should basically be an object with the functions as properties.

So, let's say we have:

var obj = {
   foo: function() { alert('foo'); }
   bar: function() { alert('bar'); }
}

Then you could do:

obj.foo(); - call a fixed name function

obj['foo'](); - dynamic name fixed arguments

obj['foo'].apply(this, args) - dynamic function name and arguments.

Edit:

One more thing I noticed:

In requirejs, when you do something like this:

define (require, function() {
    x = require('views/Foo');
    x.bar();
}

RequireJS will determine by parsing the code that you will need the 'view/Foo' module, and make sure it is loaded before executing your code.

But if you want to load a dynamic module, it won't know beforehand what module to preload, so you will have to use a callback to be notified when your module will be loaded:

define (require, function() {

    require('views/' + viewName, function(myView) {
        myView.bar(); // or 
        myView[dynamicFunc](); // ... 
    });
}
于 2012-08-28T13:29:20.463 回答