javascript - 回调此上下文

标签 javascript callback this

<分区>

在应用程序中:

var bootstrap = new Bootstrap();
bootstrap.init( this, this.onBootstrapComplete );

在 Bootstrap 中:

this.init = function( app, completeHandler ){
    _app = app;
    _completeHandler = completeHandler;
        ...
}

...

var _allReady = function(){
        _completeHandler( _app );
}

返回应用程序:

this.onBootstrapComplete = function( app )
{
        app.something();
        app.someValue = ...
}

我想在 onBootstrapComplete 中获取 this 上下文。 它有效,但看起来不正确:)

如果我想直接从 App 调用 onBootstrapComplete,我将不得不调用它 this.onBootstrapComplete( this )。

我该怎么做才能让我的 onBootstrapComplete 看起来像这样:

this.onBootstrapComplete = function()
{
        this.something();
        this.someValue = ...
}

最佳答案

我建议使用 underscore.js。参见 http://underscorejs.org/#bind了解更多信息。

this.onBootstrapComplete = _.bind( function() {
   ...
   this.someFunction(); // this context is available now
   ... 
}, this );

关于javascript - 回调此上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14546821/

相关文章:

javascript - 如何在 iframe 中切换视频静音?

php - PHP 中的 Javascript 函数 fromCharCode()

javascript - 将变量值从 C# 传递到 javascript

C++回调函数运行时错误

C++ "this"类属性

javascript - IIFE:var 与 this - 有什么区别吗?

javascript - 当使用它的函数被称为 'this' Hello")` 时, `new myFunction("指什么

javascript - 如何检查铯实体是否可见/被遮挡

javascript - 在 NodeJS 中使用相同的参数在回调函数中调用父函数

javascript - 向 for 循环添加回调