角度意外行为。自执行函数调用范围函数

时间:2015-11-11 19:41:33

标签: javascript angularjs angularjs-scope

Working code sample.

琐碎的标记:

<!DOCTYPE html>
<html ng-app="APP">
<head></head>
<body ng-controller="myController">

    <script src="angular.min.js"></script>
    <script src="controller.js"></script>
</body>
</html>

琐碎的代码示例:

angular.module('APP', []).controller('myController', function($scope) {

    $scope.test = function() {
        console.log('Weird behaviour!')
    }

    (function() {} ()); //if you comment self-executing function console will be empty

});

非常奇怪的范围行为。你能解释一下为什么会这样吗?

3 个答案:

答案 0 :(得分:6)

您无意中制作了test范围方法IIFE,目前的代码基本上是

$scope.test = (function() {
    console.log('Weird behaviour!')
})(undefined)

虽然$scope.test本身将是undefined

应该是

$scope.test = function() {
    console.log('Weird behaviour!')
};

(function() {} ());
分号很珍贵。

答案 1 :(得分:4)

$scope.test函数之后添加代码时,它有()。因此,test函数被视为self执行function

正如@estus已经说过你可以通过;结束你的功能代码来避免这个问题。

<强>代码

$scope.test = function() {
    console.log('Weird behaviour!')
}(function() {} ())

答案 2 :(得分:1)

分号仇恨者的其他答案:

java.sql.SQLException: Unable to run delete stmt on object MappedStatement: DELETE FROM `seller` WHERE `age` IN (22, 25, 26 ) : DELETE FROM `seller` WHERE `id` = ?

一般规则是在编写无分号样式时转义起始行 $scope.test = function() { console.log('Weird behaviour!') } !function(){}(); / [

(