javascript 如何在javascript对象中调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4393351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:15:37  来源:igfitidea点击:

How to call a method inside a javascript object

javascriptobjectanonymous-function

提问by joeellis

I'm just learning about how to best organize my javascript code, and I had a question regarding this small piece of code I wrote:

我只是在学习如何最好地组织我的 javascript 代码,我有一个关于我写的一小段代码的问题:

var reportsControllerIndex = {
    plotMapPoints: function(data) {
        //plots points
    },

    drawMap: function() {
        $.getJSON('/reports.json', function(data) {
            reportsControllerIndex.plotMapPoints(data);         
        });
    },

    run: function() {
        reportsControllerIndex.drawMap();
    }
};

The question is regarding calling another function of reportsControllerIndex from within the reportsControllerIndex object. I had first tried the following piece of code for the run function:

问题是关于从reportsControllerIndex 对象中调用reportsControllerIndex 的另一个函数。我首先为 run 函数尝试了以下代码:

run: function() {
    this.drawMap();
}

which worked perfectly. However, I then quickly found doing this for the drawMap function:

效果很好。但是,我很快发现为 drawMap 函数执行此操作:

drawMap: function() {
    $.getJSON('/reports.json', function(data) {
        this.plotMapPoints(data);         
    });
}

does not work, since "this" would now refer to the callback function of the getJSON call.

不起作用,因为“this”现在指的是 getJSON 调用的回调函数。

My solution was to just place reportsControllerIndex in front of all of the methods I want to call, but I was curious: is there a more relative way for calling functions within an overall object like this (much like you'd do with a class in a standard OO language)? Or am I forced to do it as I am currently, just calling the methods through the name of the object?

我的解决方案是将 reportsControllerIndex 放在我想调用的所有方法的前面,但我很好奇:是否有一种更相关的方法可以在像这样的整体对象中调用函数(很像你在标准的面向对象语言)?还是我被迫像目前那样做,只是通过对象的名称调用方法?

回答by ChaosPandion

You want to store the thisbinding in a variable.

您想将this绑定存储在变量中。

drawMap: function() {
    var _this = this;
    $.getJSON('/reports.json', function(data) {
        _this.plotMapPoints(data);         
    });
}

回答by user113716

Late answer, but jQuery has a method called jQuery.proxy()that is made for this purpose. You pass it the function along with the value of thisyou want to retain, and it will return a function that ensures thisis correct.

迟到的答案,但 jQuery 有一个为此目的而调用jQuery.proxy()的方法。您将函数以及this要保留的值传递给它,它将返回一个确保this正确的函数。

This way you don't need to define a variable.

这样你就不需要定义一个变量。

drawMap: function() {
    $.getJSON('/reports.json', $.proxy(function(data) {
        this.plotMapPoints(data);         
    }, this));
}

回答by Josiah Ruddell

You need to use a variable reference to thisoutside the getJSONfunction. getJSONsets the context of the callback within jquery.

您需要thisgetJSON函数外部使用变量引用。getJSON在 jquery 中设置回调的上下文。

Like this:

像这样:

var self = this;
$.getJSON('/reports.json', function(data) {
    self.plotMapPoints(data);         
});

回答by Danilo Souza Mor?es

plotMapPoints: function(data) {
    //plots points
}.bind(this)

when defining your function you can just add .bind(this) to set the correct context for that function.

在定义函数时,您只需添加 .bind(this) 即可为该函数设置正确的上下文。

回答by Nick Tsai

You can write it likes this:

你可以这样写:

var reportsControllerIndex = new function () {

    var self = this;

    self.plotMapPoints = function (data) {
        //plots points
    },

    self.drawMap = function () {
        $.getJSON('/reports.json', function (data) {
            self.plotMapPoints(data);         
        });
    },

    self.run = function () {
        self.drawMap();
    }
};

This class will works as same as you did, and you can still call the class method by:

这个类的工作原理和你一样,你仍然可以通过以下方式调用类方法:

reportsControllerIndex.run()

In this paradigm, I defined selfpointing to the class itself, so that you can call selfwherever you want in the class.

在这个范式中,我定义了self指向类本身,以便您可以self在类中的任何地方调用。



Farther, this paradigm can solve the thisproblem in the function that you bring as callback to another funciton:

更进一步,这个范式可以解决this你作为回调带到另一个函数的函数中的问题:

plotMapPoints: function(data) {
    console.log(this);
    // Need a this referring to the class itself
    // It's inconvenient to bring this as parameter
},