【问题标题】:Cannot define a method with "this"无法用“this”定义方法
【发布时间】:2017-03-06 17:30:13
【问题描述】:

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

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 可以定义为私有方法。但是,以下定义不起作用:

    this.init = function () {
        this.initFolder()
        ...
    }

    this.initFolder = function () {
        // the code inside does not mention "this"
        ...
    }

有谁知道为什么我不能用this 定义initFolder

【问题讨论】:

  • 请检查我的回答是否能解决您的疑问

标签: javascript oop this angular-services


【解决方案1】:

在函数外部创建对this 的引用,并在函数内部使用它。这样,您在定义函数并在函数内部重用该引用时就有对 this 的引用,否则 this 可能会在实际调用该方法时指向不同的东西,例如浏览器窗口。

var me = this;
this.init = function () {
    // reference to this
    me.initFolder()
    ...
}

我建议阅读How does the "this" keyword work?,它的答案写得很好。

【讨论】:

    【解决方案2】:

    这与 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"
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 2011-04-30
      • 2015-05-25
      • 1970-01-01
      相关资源
      最近更新 更多