Forgive me for what may seem like a silly question, but I believe it will help clarify my understanding.
Let's dive into JavaScript:
var firstName = "Peter",
lastName = "Ally";
function showFullName () {
// The "this" inside this function refers to the window object
// since showFullName() is in the global scope, just like firstName and lastName
console.log (this.firstName + " " + this.lastName);
}
var person = {
firstName :"Penelope",
lastName :"Barrymore",
showFullName:function () {
// The "this" below points to the person object, as shown by person invoking the function.
console.log (this.firstName + " " + this.lastName);
}
}
showFullName(); // Peter Ally
window.showFullName(); // Peter Ally
This makes sense to me. Now, transitioning to an Angular controller:
<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>
Shouldn't the second
line still log window
because the controller function is in the global scope (I think)?
However, it returns an Object. Why?
Can I use this.myTestFunction
without using ControllerAs
syntax? What sets them apart?
Why does the last line also log object
(in myTestFunction) when I am simply returning this from within?
I'm a bit confused about all of this. Could someone break it down simply?
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}