AngularJS 提供程序中的“this”指的是什么?
What does `this` refer to inside an AngularJS provider?
this
在 AngularJS 提供商中指的是什么?
And the value it is assigned is based exclusively on the object that
invokes the this Function.
Source: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
基于以上我认为 this
引用了调用 this
所在函数的对象。
所以在下面的例子中...
sth.provider('Cat', function CatProvider() {
var resourceName = 'user';
this.resourceName = function(value) {
if (value === undefined) {
return resourceName;
}
resourceName = value;
return this;
};
this.$get = function($q, $http, $rootScope) {
...
}
}
...this
是指 sth
还是 .provider
?
我有点懵
指的是CatProvider
函数。如果您查看 AngularJS angular.Module.provider()
的文档,您将看到以下描述:
Register a provider function with the $injector. Provider functions
are constructor functions, whose instances are responsible for
"providing" a factory for a service.
由于提供者函数是构造函数,那么这仅表明函数本身已被实例化,因此,this
,引用实例化的CatProvider
函数的实例。
在您使用的 EcmaScript 5 中,this 指的是它在...
中使用的函数
function Jim() {
// this is the Jim function
var self = this;
function Fred() {
// this is the Fred function
this.name='fred'; // I have added a name property to the Fred function
// I can access Jim here by referencing self
self.name='jim'; // I have added a name property to the Jim function
}
}
这就是我们在 EcmaScript 5 中的做法。
在 EcmaScript 6 中,这一切都改变了,上面的内容不再适用。您很快就会在附近的浏览器中遇到 EcmaScript 6 :)
this
在 AngularJS 提供商中指的是什么?
And the value it is assigned is based exclusively on the object that invokes the this Function. Source: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
基于以上我认为 this
引用了调用 this
所在函数的对象。
所以在下面的例子中...
sth.provider('Cat', function CatProvider() {
var resourceName = 'user';
this.resourceName = function(value) {
if (value === undefined) {
return resourceName;
}
resourceName = value;
return this;
};
this.$get = function($q, $http, $rootScope) {
...
}
}
...this
是指 sth
还是 .provider
?
我有点懵
指的是CatProvider
函数。如果您查看 AngularJS angular.Module.provider()
的文档,您将看到以下描述:
Register a provider function with the $injector. Provider functions are constructor functions, whose instances are responsible for "providing" a factory for a service.
由于提供者函数是构造函数,那么这仅表明函数本身已被实例化,因此,this
,引用实例化的CatProvider
函数的实例。
在您使用的 EcmaScript 5 中,this 指的是它在...
中使用的函数function Jim() {
// this is the Jim function
var self = this;
function Fred() {
// this is the Fred function
this.name='fred'; // I have added a name property to the Fred function
// I can access Jim here by referencing self
self.name='jim'; // I have added a name property to the Jim function
}
}
这就是我们在 EcmaScript 5 中的做法。
在 EcmaScript 6 中,这一切都改变了,上面的内容不再适用。您很快就会在附近的浏览器中遇到 EcmaScript 6 :)