Joe*_*ers 3 javascript angularjs
我对Angular很新,但我在我的应用程序中调试的最近一个问题如下:
假设我正在将新指令附加到另一个.js文件中定义的现有模块.当我使用以下语法时:
angular
.module('myApp')
.directive('ratingStars', ratingStars)
;
var ratingStars = function(){
return {
restrict: 'EA',
scope: {thisRating : '=rating'},
templateUrl: '/my.template.html'
};
};
Run Code Online (Sandbox Code Playgroud)
我会得到一个错误,沿着"Argument'fn'不是一个函数,未定义".
但是,我可以使用以下代码修复代码(注意直接使用函数而不是分配给var).
angular
.module('myApp')
.directive('ratingStars', ratingStars)
;
function ratingStars(){
return {
restrict: 'EA',
scope: {thisRating : '=rating'},
templateUrl: '/my.template.html'
};
}
Run Code Online (Sandbox Code Playgroud)
获取函数和赋值给var之间的逻辑区别是什么,而不是直接定义函数?是否有某种变量悬挂?我的var只是那个文件的本地吗?
非常感谢.
它与顶部吊装有关.
获取函数和赋值给var之间的逻辑区别是什么,而不是直接定义函数?
在第一个脚本中,
您的脚本解释如下.
var ratingStars;
angular
.module('myApp')
.directive('ratingStars', ratingStars);
ratingStars = function() {
return {
restrict: 'EA',
scope: { thisRating: '=rating' },
templateUrl: '/my.template.html'
};
};
Run Code Online (Sandbox Code Playgroud)
所以,你可以看到,var ratingStars是declared first and assigned it to the directive definition.Its因为声明使用的JavaScript中的变量在var函数范围block scope或全局范围内被提升.
But actual definition will occur after that.
在第二个脚本中,
您的function definition,将被定义在全局代码的顶部.所以,它得到了正确的解释.
所以,第一个使用函数表达式,其中variable getting top hoisted
但not actual function definition第二个使用功能定义
哪里 function defination itself getting top hoisted
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |