我正在将一个函数: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();
GeneratePersonQuery
必须在main
之外(如果它是内部函数,则可以访问父作用域)。expression