"$this"的这两种用法有何不同?



我现在正在研究一些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() {
/* ... */
}
}

最新更新