Angular 的新手,我正在尝试遵循 JSLint(由 Douglas Crockford 编写)的建议,即根本不要在 JS 中使用 this
。
如何防止自己在 Angular 中使用 this
?到目前为止,我看到的所有教程都依赖于使用 this
并且 SO 搜索没有得到任何答案。
为了清楚起见,假设我正在尝试编写这个 Controller :
app.controller('StoreController', function() {
this.products = {};
});
如何访问 Controller 对象以便添加 products
属性?
var my_controller = app.controller('StoreController', function() {
});
my_controller.products = {}; // Maybe like this?
最佳答案
注入(inject) $scope
,例如:
app.controller('StoreController', function($scope) {
$scope.products = {};
});
以下是关于它们的更多信息:https://docs.angularjs.org/guide/scope
此外,在使用服务之类的东西时,你可以避免this
通过保持本地状态并返回接口(interface)对象。例如:
.service('MyService', function(){
// state
var mystate = {};
// interface object
return {
someExposedFunc: function(){
}
};
});
不过,我想指出的是,我看不出有什么理由应该避免使用 this
使用 Angular 时。我想使用 $scope
在阅读 Controller 代码时具有更多语义实用性,但在使用服务之类的东西时,我通过创建像 this.somefunc = ...
这样的公开函数来编写更少的代码.
关于javascript - 如何不在 Angular 中使用 'this'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34936001/