我正在分析angular.forEach
函数:
以下是angular.forEach
的代码:
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);
上下文的描述是:
对象成为迭代器函数的上下文(this)。
我提出了一些问题:
为什么使用和何时有用的参数 context ?!
为什么使用这个代替日志变量?
答案 0 :(得分:6)
在您提供的示例中,使用select
name, location,
substr(code, 1, instr(code,'-')-1) as id,
substr(code, instr(code,'-')+1) as per
from orig_table;
或直接使用this
是相同的。这是因为log array
和callback
中使用的forEach method
定义在同一log array
中。
但是,在某些情况下scope
的定义可能与callback
不同scope
。然后呼叫应如下所示:
log array
在这种情况下,我们应该在回调中使用angular.forEach(values, getNames, log);
,因为它会引用this
,而log array
是在不同的scope
中定义的。
修改强>
请参阅此 JSFiddle demo 以及显示我所解释内容的代码。
var getNames = function(value, key) {
this.push(key + ': ' + value);
};
var processObject = function(){
var log = [];
// Now getNames callback is defined in a different
// scope than log
angular.forEach(values, getNames, log);
return log;
}
var values = {name: 'misko', gender: 'male'};
var resultArray = processObject(values);
// This gives same result as your exmple
alert(resultArray);
答案 1 :(得分:2)
从未使用过angular.forEach(),但它看起来很简单。
var hello = {
message: 'Ok'
};
angular.forEach([' I', ' said', ' hello'], function (value) {
this.message += value;
}, hello);
console.log(hello.message);
1 /它会记录'好的,我说过你好'所以基本上'context'参数将允许你更新你将参考的任何对象。用例真的很广......
2 /我认为它与执行上下文有关。词汇环境因此this
必须与angular.forEach的实现方式有关。只需检查angularjs源代码。