猿问

angularJs闭包中使用$watch监听的执行过程

监听函数在定义之后不是就会立即执行一次吗,那为什么仍然不能显示呢,能解释一下具体的内部执行顺序吗?

https://img3.mukewang.com/5c306c5100019a1501890192.jpg

Cats萌萌
浏览 450回答 1
1回答

一只斗牛犬

你可以试一下下面这段代码的执行结果就知道自己的问题在哪里了,这是js中的一个很典型的闭包问题,可以使用匿名函数解决.for(var i = 0;i<3;i++){&nbsp; &nbsp; setTimeout(function(){&nbsp; &nbsp; &nbsp; console.log(i);&nbsp; &nbsp; }, 200);};for(var j = 0;j<3;j++){&nbsp; &nbsp; (function (j) {&nbsp; &nbsp; &nbsp; setTimeout(function(){&nbsp; &nbsp; &nbsp; &nbsp; console.log('j',j);&nbsp; &nbsp; &nbsp; }, 200)&nbsp; &nbsp; })(j);};你所监听的一直是data[3],可以修改如下:&nbsp; &nbsp; &nbsp;(function(i,itemElement){&nbsp; &nbsp; &nbsp; &nbsp; var watcherFn = function (watchScope) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return watchScope.$eval(propertyExpression, data[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; scope.$watch(watcherFn, function (newValue, oldValue) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; itemElement.text(newValue);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp;&nbsp; &nbsp; })(i,itemElement)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答