从嵌套函数访问外部对象(使用主干.js

Accessing an outer object from a nested function (Using backbone.js

本文关键字:js 对象 嵌套 函数 访问 外部      更新时间:2023-09-26

我正在使用 backbone .js 构建一个 js 重应用程序。 我遇到过几次的一个问题是如何从深度嵌套函数调用外部对象。 在下面的代码示例中,我想在发生幻灯片事件时调用 custom_function 事件。 最好的方法是什么?

App.Views.Category = Backbone.View.extend({
    ....,
    render: function () {
        $('#slider').slider({
            min:0,
            max:100,
            slide: function(event, ui) {
               //HOW DO I CALL THE custom_function from here????
            },
        });
    },
    custom_function: function() {
       alert('in custom function');
    },

});

非洲自卫队

有两个常见的选项。

您可以this到像 that 这样的对象中,也可以self然后调用它。

render: function () {
    var that = this;
    $('#slider').slider({
        min:0,
        max:100,
        slide: function(event, ui) {
           //HOW DO I CALL THE custom_function from here????
           that.custom_function();
        },
    });
},

或者,您可以绑定函数的上下文。

render: function () {
    $('#slider').slider({
        min:0,
        max:100,
        slide: (function(event, ui) {
           //HOW DO I CALL THE custom_function from here????
           this.custom_function();
        }).bind(this),
    });
}, 

Function.prototype.bind 仅是 ES5,因此请使用 _.bind$.proxy 进行跨浏览器支持