javascript - 如何将回调函数包装在其他回调函数中并从那里调用?

标签 javascript callback typescript

以下是我的代码:

        var me = this;
        gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, function (authResult: any) {
            if (authResult && !authResult.error) {
                me.accessToken = authResult.access_token;

            } else {

              //TODO : show error in front end
            }
        });

当我像这样使用回调函数时。

gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, AuthResult);

function AuthResult(authResult: any) {
                if (authResult && !authResult.error) {
                    me.accessToken = authResult.access_token;

                } else {

                  //TODO : show error in front end
                }

我在那个回调函数中没有得到 me 属性

我如何将回调函数包装在其他回调函数中,这样我也可以在 JS 中获取作用域

最佳答案

使用粗箭头:

    gapi.auth.authorize({ client_id: client, scope: scope, immediate: true },AuthResult);

    const AuthResult = (authResult: any) => {
            if (authResult && !authResult.error) {
                this.accessToken = authResult.access_token;

            } else {
              //TODO : show error in front end
            }

更多

不要使用 .bind :https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html至少现在还没有

关于javascript - 如何将回调函数包装在其他回调函数中并从那里调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36321191/

相关文章:

javascript - D3/Angular 获取窗口大小

c++ - 为什么我们需要在运行时使用函数指针调用这些函数。我们也可以直接调用他们

php - 带有回调OOP的php中的array_map

javascript - Angular Router - 如何创建没有正斜杠的动态路由

javascript - 在鼠标按下控制时使用缓动效果向左/右动画 div

使组件动态跟随另一个组件的Javascript

c - 通过 shell (cat) 或通过程序 (fread) 读取 proc 文件的区别

node.js - TS2307 : Cannot find module 'express'

javascript - 从 react-router-dom 属性 'sumParams' 升级版本 4 useParams () 后 TypeScript 错误在类型 '{}' 上不存在

node.js - NRWL NX - 为什么我得到 "Cannot find name ' describe '"when running "ng serve express”?