javascript - 无法使用 "this"定义方法

标签 javascript oop this angular-services

我编写了以下代码,它运行:

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/

相关文章:

c++ - 带有 std::thread 和 this 的 ctor 初始值设定项列表

javascript - Node.js 和浏览器中函数上下文(this)的区别

javascript - 在 Android 手机浏览器中播放声音

javascript - 返回 Javascript 类内部元素中元素的当前索引

javascript - 查找数组中的数字是否介于两个数字之间并输出介于两者之间的值的数量

java - 调用父类(super class)型方法会创建一个新的父类(super class)型对象吗?

Javascript 原型(prototype) - 不仅适用于实例对象?

javascript - JS 类中的方法不带函数

ruby - 了解 ruby​​ 中的方法调用

c++ - 这个指针的使用