我编写了以下代码,它运行:
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"
...
}
}
我意识到,要在 reslove
中使用 codeService.init
,我需要使用 this
定义 init
,而 initFolder
可以定义为私有(private)方法。但是,以下定义不起作用:
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()
...
}
我建议阅读How does the "this" keyword work? ,它有一个写得很好的答案。
关于javascript - 无法使用 "this"定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42631950/