Reputation: 193
I'm studying up on some AngularJS code at the moment and I noticed two different uses of $this
in the definition of an AngularJS factory:
module.factory('f_sys', function(...) {
var $this = { data : { id: "123" } };
...
function _updateSystem(d) {
return $this.data.id == "123"; // (true)
}
$this.init = function() {
...
}
...
return $this;
});
What's happening here? Is the init
function being added as another key to the var $this
object? Is it treated just like another function (i.e. like _updateSystem
)?
Upvotes: 0
Views: 36
Reputation: 349908
init
is not like the other function. It is like you say: it becomes a property of the $this
object. So you can call $this.init()
, but to call _updateSystem
you cannot write $this._updateSystem()
. And as you return $this
to the caller, the caller can call init()
, but not _updateSystem()
.
The construction of $this
is the same as if you would have written it in one single assignment:
var $this = {
data: {
id: "123"
},
init: function() {
/* ... */
}
}
Or in a more modern (ES6) syntax:
const $this = {
data: {
id: "123"
},
init() {
/* ... */
}
}
Upvotes: 1