2015-11-11 32 views
5

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 

}); 

而且很奇怪的範圍的行爲。你能解釋爲什麼會發生這種情況嗎?

+0

我相信你知道這個j avascript特定的代碼風格...這裏是一個例子:jsfiddle.net/prfy9eso。值得注意的是,對於該示例的解釋以不同的方式工作(空行在第二個示例中更改代碼行爲,但不會更改角示例中的行爲)。 – Spirit

+1

'return'[已知例外](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/return#Automatic_Semicolon_Insertion)。請注意關於「返回語句後無法訪問的代碼」的註釋,它僅涉及Firefox,但使用正確配置的linter可能會阻止這兩種情況。 – estus

+0

還'拋出','繼續','打破'。 [spec](http://ecma-international.org/ecma-262/5.1/#sec-7.9) –

回答

6

你非故意test範圍方法IIFE,而目前的代碼基本上

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

雖然$scope.test本身將undefined

應該

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

(function() {}()); 

分號珍貴。

+1

好解釋estus..appreciated +1 –

+1

@PankajParkar,謝謝,答案几乎同時出現。 – estus

+0

但你的比我好;) –

4

由於您在$scope.test功能之後添加了代碼,因此它具有()。如此,是因爲它是作爲@estus已經說了,你可以迴避這個問題由;結束你的函數代碼test功能被認爲是self執行function

代碼

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

爲分號仇敵其他答案:

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

!function(){}(); 

這是一般規則來逃避STARTLINE [/(的,當你寫分號少風格:

;[].forEach.apply(arguments, iterator) 
;(function(){})()