我可能會因爲問這樣一個愚蠢的問題而受到轟炸,但它更多的是一個問題,這將有助於使我的理解清晰。Angular Controller中的這個關鍵字
在JavaScript所以,
var firstName = "Peter",
lastName = "Ally";
function showFullName() {
// "this" inside this function will have the value of the window object
// because the showFullName() function is defined in the global scope, just like the firstName and lastName
console.log (this.firstName + " " + this.lastName);
}
var person = {
firstName :"Penelope",
lastName :"Barrymore",
showFullName:function() {
// "this" on the line below refers to the person object, because the showFullName function will be invoked by person object.
console.log (this.firstName + " " + this.lastName);
}
}
showFullName(); // Peter Ally
// window is the object that all global variables and functions are defined on, hence:
window.showFullName(); // Peter Ally
這我很清楚。現在的角度控制器,當我們試圖複製此,
<script>
var app = angular.module("myApp", []);
console.log("Before Controller",this);
app.controller("myCtrl", function($scope) {
console.log(this);
$scope.firstName = "John";
$scope.lastName = "Doe";
this.myTestFunction = function(){
return this;
}
console.log("In test function ",this.myTestFunction());
});
</script>
的second
線仍然應登錄window
權控制器功能在全球範圍內定義(我想)。 But in turn, it returns an Object. Why ?
另外,我可以在不使用ControllerAs
語法的情況下使用this.myTestFunction
。兩者有什麼區別?
Why the last line also logs
object (In myTestFunction) when I am just simply returning this from within
?
我不確定所有這些。有人可以用簡單的術語解釋嗎?
Before Controller Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
VM2143 tryit.asp?filename=try_ng_module:5 Object {}
VM2408 tryit.asp?filename=try_ng_module:12 In test function Object {myTestFunction: function}
控制器功能未在全局範圍內定義。可以清楚地看到它是一個函數的參數'angular.controller()' – charlietfl