JavaScript:如何获取闭包的值

时间:2018-08-02 05:20:57

标签: javascript closures

我正在将一个函数:x => x.FirstName == person.name发送到另一个函数作为参数,我想获取person.name的值(它成为一个闭包):

function main() {
    var person = {name : 'john'}
    var query = GeneratePersonQuery()
        .where(x => x.FirstName == person.name)
    
}
function GeneratePersonQuery() {
    var _fruits = {FirstName : 'firstname', LastName : 'lastname' /* ... */ };
    var _where = function (expression) {
        //bind expression with fruits for intellisense
        expression.call(null, _fruits);
        var parts = expression.toString().split(' => ');//["x", "x.FirstName == person.name"]
        var condition = parts[1].split(' ');            //["x.FirstName", "==", "person.name"]
        var column = condition[0].split('.')[1];        //"FirstName"
        var operator = condition[1];                    //"=="
        var value = condition[2];                       //"person.name"

        //return "SELECT * FROM PEOPLE WHERE " + column + ' ' + operator + ' ' + eval(value);
        //Error: person is not defined..
    }
    return { where : _where }
}
main();

  1. 函数GeneratePersonQuery必须在main之外(如果它是内部函数,则可以访问父作用域)。
  2. 我不想用其他“容器”包装expression

0 个答案:

没有答案