繁体   English   中英

如何在javascript对象中调用方法

[英]How to call a method inside a javascript object

我刚学习如何最好地组织我的javascript代码,我对我写的这小段代码有一个疑问:

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

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

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

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

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

这很完美。 但是,我很快发现这是为drawMap函数做的:

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

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

我的解决方案是将reportsControllerIndex放在我想要调用的所有方法的前面,但我很好奇:是否有一种更相对的方式来调用像这样的整体对象中的函数(就像你在一个类中所做的那样)标准的OO语言)? 或者我现在被迫这样做,只是通过对象的名称调用方法?

您希望this绑定存储在变量中。

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

迟到的答案,但jQuery有一个名为jQuery.proxy()的方法,它是为此目的而制作的。 你通过它的价值以及功能this要保留,它将返回,确保功能this是正确的。

这样您就不需要定义变量了。

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

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

像这样:

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

在定义函数时,您可以添加.bind(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();
    }
};

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

reportsControllerIndex.run()

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


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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM