2017-03-06 14 views
0

我寫了下面的代碼,它運行定義一個方法:不能與「此」

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,我需要定義initthis,而initFolder可定義爲私有方法。但是,下面的定義不工作:

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

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

有誰知道爲什麼我不能this定義initFolder

+0

請檢查,如果我的答案清除您懷疑 –

回答

1

這與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服務

當你打電話給你的服務,你在做什麼,但調用構造函數來創建該對象,您可以使用的一個實例。

然後,您使用的所有方法都鏈接到傳遞給您的控制器的對象實例,然後使用該對象實例。

現在,當一個函數被定義在那個不直接在該服務下的對象中時,由於上面解釋的概念,這不正確。

因此,您必須將此值存儲在某個變量中,以便在函數內部進一步使用它。

在特定情況下,你可以把它作爲工作:

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

在函數外創建對this的引用,並在函數內部使用該函數。這樣,您在定義函數時重新引用this,並在函數內重用該引用,否則this可能會在實際調用瀏覽器窗口時指向不同的東西。

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

我建議你閱讀過How does the "this" keyword work?,它有一個很好的書面答覆。