无法使用"这个"定义一个方法。

时间:2017-03-06 17:30:13

标签: 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"
        ...
    }
}    

我意识到,要在codeService.init中使用reslove,我需要使用init定义this,而initFolder可以定义为私有方法。但是,以下定义不起作用:

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

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

有谁知道为什么我无法使用initFolder定义this

2 个答案:

答案 0 :(得分:2)

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

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

我建议阅读How does the "this" keyword work?,它有一个非常好的答案。

答案 1 :(得分:1)

这与javascript中this在盒装范围内的行为方式有关。

例如:

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服务

当你调用你的服务时,除了调用构造函数来创建你可以使用的那个对象的实例之外什么都不做。

然后,您使用的所有方法都链接到传递给控制器​​的对象实例,然后再使用它。

现在,当一个函数被定义在该对象内部并且不直接位于该服务之下时,由于上面解释的概念,这个行为不正确。

因此,您必须将此值存储在某个变量中,以便在函数内进一步使用它。

在您的具体情况下,您可以将其作为:

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