我现在正在研究一些AngularJS代码,我注意到$this
在AngularJS工厂的定义中有两种不同的用途:
module.factory('f_sys', function(...) {
var $this = { data : { id: "123" } };
...
function _updateSystem(d) {
return $this.data.id == "123"; // (true)
}
$this.init = function() {
...
}
...
return $this;
});
这是怎么回事?是否将init
函数作为另一个键添加到var $this
对象?它是否像另一个函数一样对待(即像_updateSystem
(?
init
不像其他函数。就像你说的:它成为$this
对象的属性。所以你可以调用$this.init()
,但要调用_updateSystem
你不能写$this._updateSystem()
。当您将$this
返回给呼叫者时,呼叫者可以呼叫init()
,但不能_updateSystem()
。
$this
的构造与在单个作业中编写它相同:
var $this = {
data: {
id: "123"
},
init: function() {
/* ... */
}
}
或者使用更现代的 (ES6( 语法:
const $this = {
data: {
id: "123"
},
init() {
/* ... */
}
}