如何在同一个对象中调用另一个函数? [英] How to call another function within the same object?

查看:142
本文介绍了如何在同一个对象中调用另一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let role = {
    test: (variable) => {
        // How do I call toLog(variable) from here?
    },
    toLog: (variable) => {
        console.log(variable);
    }
};

我想在test()函数中调用toLog()函数但我是不知道怎么做。

I'd like to call the toLog() function within the test() function but I'm unaware how to.

推荐答案

标准JS函数使用动态绑定,这个取决于谁在运行时调用方法,所以如果我们使用 role.test()调用它,它将绑定这个角色

Standard JS functions use dynamic binding, this is dependent on who's calling the method on runtime, so if we call it using role.test(), it will bind this to role.

箭头函数绑定在当前的背景下。例如,如果代码是在浏览器控制台中写的,则绑定到窗口对象。这称为静态词法绑定,这意味着将绑定到它所定义的闭包。

Arrow functions bind this to the current context. For example, if the code was writtern in the browser's console, this is bound to the window object. This is called static lexical binding, which means binding this to the closure it was defined in.

如果您不使用箭头功能,将在 role 调用时指向对象本身:

If you won't use arrow functions, this will point to the object itself when called by role:

const role = {
    test(variable){
        this.toLog(variable);
    },
    toLog(variable) {
        console.log(variable);
    }
};

role.test(5);

在这种情况下,我们不想将这个绑定到外部上下文,因此我们将跳过静态绑定,转而使用动态绑定。

In this case, we don't want to bind this to the outer context, so we'll skip the static binding in favor of the dynamic one.

但是,如果我们将此方法用作回调,则动态绑定将根据谁在运行来更改方法。为了防止这种情况,我们必须使用 bind 来创建对 role 的显式静态绑定。

However, if we'll use this method as a callback, dynamic binding will change this according to who's running the method. To prevent that, we'll have to use bind to create an explicit static binding to role.

const role = {
  test(variable) {
      this.toLog(variable);
    },
    toLog(variable) {
      console.log(variable);
    }
};

let test = role.test;

try {
  test(20); // will throw an error - this.toLog is not a function - because this points to window
} catch (e) {
  console.log(e);
}

test = role.test.bind(role);

test(25); // will work because it's staticly binded to role

这篇关于如何在同一个对象中调用另一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆