如何在函数中预先计算值查找

时间:2013-04-02 22:41:02

标签: javascript jquery

我正在试图找出正确的语法“预先计算”属性值,以便在下面的“withPrefix”函数中查找,以便我可以传递该函数,它不会依赖于当前的值x在执行时。

var a = { 
    one: 'First Name',
    two: 'Last Name'
};

var x = 'one';
var withPrefix = function(value) {
    return a[x] + ": " + value;
};

console.log(withPrefix);

当然这是一个人为的例子,真实的例子更复杂,但试图将其简化为最简单的情况。 console.log输出显示:

function (value) {
    return a[x] + ": " + value;
} 

但我希望它像:

function (value) {
    return a['one'] + ": " + value;
} 

我使用jQuery和RequireJS。如果这些库中的任何一个有任何帮助,这将是一个可接受的解决方案,但我怀疑这是一种纯粹的javascript方式。

3 个答案:

答案 0 :(得分:1)

您可以通过部分功能应用和bind获得一些乐趣:

function masterFunc(x, value) {
    return a[x] + ": " + value;
}
var xValFunc = masterFunc.bind(null, 'one');
console.log(xValFunc('foo')); // First Name: foo

答案 1 :(得分:0)

如果我理解的话。你想做一个本地范围尝试这样的事情:

var withPrefix = (function(){
  //create a new scope
        /* all viables created here cant be seen by the souronding code */
  var x = "one"
    , a = 
      { one: "First Name"
      , two: "Last Name"
      }
  return function(value){
    // the withPrefix function
    return a[x] + ": " + value //make the string using the Local object a
  }
}())
withPrefix("foo") // returns: "First Name: foo"
console.log(a) // returns undefined
console.log(x) // returns undefined

答案 2 :(得分:0)

那么,你想要的是封闭?使用工厂函数(生成函数的函数):

function make_withPrefix (x) {
    return function (value) {
        return a[x] + ": " + value;
    }
}

所以现在你可以生成适当的withPrefix函数:

var withPrefix_one = make_withPrefix('one');
var withPrefix_two = make_withPrefix('two');

withPrefix_one('Han');   // returns "First Name : Han"
withPrefix_two('Solo');  // returns "Second Name : Solo"

只是简单的旧javascript。没有花哨的新功能,如绑定或任何东西,并没有可怕的引用地狱的字符串。自Netscape Navigator和IE1支持