如何在同一个对象中调用另一个函数?

uns*_*ska 13 javascript ecmascript-6

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

我想在test()函数中调用toLog()函数,但我不知道如何.

Ori*_*ori 16

标准JS函数使用动态绑定,this取决于谁在运行时调用该方法,因此如果我们使用role.test()它调用它,它将绑定thisrole.

箭头函数绑定this到当前上下文.例如,如果代码在浏览器的控制台中this是写的,则绑定到该window对象.这称为静态词法绑定,这意味着绑定this到它所定义的闭包.

如果您不使用箭头函数,this则在调用时将指向对象本身role:

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

role.test(5);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我们不想绑定this到外部上下文,因此我们将跳过静态绑定以支持动态绑定.

但是,如果我们将此方法用作回调,则动态绑定将this根据运行该方法的人员而更改.为了防止这种情况,我们必须使用bind创建显式静态绑定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
Run Code Online (Sandbox Code Playgroud)

  • 非常好的解释谢谢! (2认同)