[英]Cannot define a method with “this”
我编写了以下代码,该代码可以运行:
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('editor', {
resolve: {
init: ['codeService', function (codeService) {
return codeService.init()
}]
}
...
})
app.service('codeService', ['$http', function ($http) {
this.init = function () {
initFolder()
...
}
var initFolder = function () {
// the code inside does not mention "this"
...
}
}
我认识到,使用codeService.init
在reslove
,我需要定义init
与this
,而initFolder
可以被定义为私有方法。 但是,以下定义不起作用:
this.init = function () {
this.initFolder()
...
}
this.initFolder = function () {
// the code inside does not mention "this"
...
}
有谁知道为什么我不能用this
来定义initFolder
?
在函数外部创建this
的引用,并在函数内部使用该引用。 这样,你有一个参考this
你定义的功能和重用功能内部的参考时间,否则this
可能指向东西的方法实际上被称为像浏览器窗口的时间不同。
var me = this;
this.init = function () {
// reference to this
me.initFolder()
...
}
建议您阅读“ this”关键字如何工作? ,它有一个很好的书面答案。
这与该办法做到this
表现在JavaScript盒装范围内。
例如:
var obj = {
firstname: "rahul",
lastname: "arora"
getName: function(){
console.log(this);//will output the object as this here points to the object it is defined under
}
};
obj.getName();
鉴于
var obj = {
firstname: "rahul",
lastname: "arora"
getName: function(){
function getFullName(){
console.log(this);//this refers to the window and not to the object this time
}
getFullName();
}
};
obj.getName();
这就是javascript的工作方式。 有点奇怪,但这就是它的设计方式。
将相同的概念应用于您的AngularJS服务
调用服务时,除了调用构造函数创建该对象的实例(您可以使用)外,您什么都没有做。
然后,将您使用的所有方法链接到传递给您然后使用的控制器的对象实例。
现在,当在不直接在该服务下的对象内定义函数时,由于上面解释的概念,该函数的行为不正确。
因此,您必须将this的值存储在某个变量中,才能在函数内部进一步使用它。
在您的特定情况下,您可以使其工作如下:
var self = this;
this.init = function () {
self.initFolder()
/*since the function is called from inside a function which is inside an object,
this will not point to that instance of the object in this scenario.
Therefore, you have to store the value of this in a variable to make sure you use that inside this function to make it work properly.*/
...
}
this.initFolder = function () {
// the code inside does not mention "this"
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.