簡體   English   中英

無法使用“ this”定義方法

[英]Cannot define a method with “this”

我編寫了以下代碼,該代碼可以運行:

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.initreslove ,我需要定義initthis ,而initFolder可以被定義為私有方法。 但是,以下定義不起作用:

    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()
    ...
}

建議您閱讀“ this”關鍵字如何工作? ,它有一個很好的書面答案。

這與該辦法做到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"
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM