2013-08-01 31 views
2

下面是我從這個Named parameters in javascript拿到代碼:命名參數,而不覆蓋現有值

var parameterfy = (function() { 
    var pattern = /function[^(]*\(([^)]*)\)/; 

    return function (func) { 
     // fails horribly for parameterless functions ;) 
     var args = func.toString().match(pattern)[1].split(/,\s*/); 

     return function() { 
      var named_params = arguments[arguments.length - 1]; 
      if (typeof named_params === 'object') { 
       var params = [].slice.call(arguments, 0, -1); 
       if (params.length < args.length) { 
        for (var i = params.length, l = args.length; i < l; i++) { 
         params.push(named_params[args[i]]); 
        } 
        return func.apply(this, params); 
       } 
      } 
      return func.apply(null, arguments); 
     }; 
    }; 
}()); 

var myObject = { 
    first: "", 
    second: "", 
    third: "" 
}; 

var foo = parameterfy(function (a, b, c) { 
     //console.log('a is ' + a, ' | b is ' + b, ' | c is ' + c); 
     myObject.first = a; 
     myObject.second = b; 
     myObject.third = c; 
     console.log("first " + myObject.first + " second " + myObject.second + " third " + myObject.third); 
}); 


foo(1, 2, 3); // gives 1, 2, 3 
foo({a: 11, c: 13}); // gives 11, undefined, 13 
foo({ a: 11, b:myObject.second, c: 13 }); // in order to avoid undefined, this is 

需要注意的是,在foo秒情況下,我得到了undefined,因爲我沒有通過b所以我不得不使用第三個實例來傳遞b的當前值。

反正是有讓這個如果我沒有在這種情況下傳遞一個值,例如,b值,因此,它仍然會更新ac給定值,但保留了b值?

+0

嚴重......爲什麼?只需使用每個人使用的標準模式,並遠離雙倍。 – plalx

+0

你指的是哪種標準模式?我有大約30個變量需要定期初始化和更新。 – premsh

+0

查看我的回答;) – plalx

回答

2

類似下面的可能工作:

var foo = parameterfy(function (a, b, c) { 
    //console.log('a is ' + a, ' | b is ' + b, ' | c is ' + c); 
    if(typeof a != 'undefined'){myObject.first = a;} 
    if(typeof b != 'undefined'){myObject.second = b;} 
    if(typeof c != 'undefined'){myObject.third = c;} 
    console.log("first " + myObject.first + " second " + myObject.second + " third " + myObject.third); 
}); 
+0

作品:) Thanks user506069! 如果有人知道這個問題或更好的命名參數技術一般更好的方法,請讓我知道。 – premsh

1

這裏已成功使用多年命名的參數標準,你應該堅持下去:

function myFunction(options) { 
    console.log(options.first); 
    console.log(options.second); 
    console.log(options.third); 
} 

myFunction({ 
    first: 1, 
    second: 2, 
    third: 3 
}); 
+0

我想你是對的,似乎我過分複雜的東西......謝謝。 – premsh