2016-12-25 190 views
10
let role = { 
    test: (variable) => { 
     // How do I call toLog(variable) from here? 
    }, 
    toLog: (variable) => { 
     console.log(variable); 
    } 
}; 

我想调用test()函数内的toLog()函数,但我不知道如何去做。如何在同一个对象中调用另一个函数?

+3

'role.toLog()'或使用一个类,所以你可以简单地使用'this.toLog()' – Ties

+2

[在这里你不需要他们不要使用箭头功能!](http://stackoverflow.com/q/34361379/1048572)通过方法语法(在对象字面量中),您可以照常调用'this.toLog'。 – Bergi

回答

11

标准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);

在这种情况下,我们不希望绑定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

相关问题