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

Ant*_*hin 5 javascript angularjs angularjs-scope

工作代码示例.

琐碎的标记:

<!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>
Run Code Online (Sandbox Code Playgroud)

琐碎的代码示例:

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

});
Run Code Online (Sandbox Code Playgroud)

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

Est*_*ask 6

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

$scope.test = (function() {
    console.log('Weird behaviour!')
})(undefined)
Run Code Online (Sandbox Code Playgroud)

虽然$scope.test它本身就是undefined.

它应该是

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

(function() {} ());
Run Code Online (Sandbox Code Playgroud)

分号很珍贵.