gpt4 book ai didi

javascript - javascript 函数的绑定(bind)方法存在问题

转载 作者:行者123 更新时间:2023-11-28 13:27:29 24 4
gpt4 key购买 nike

我对以下脚本在 Chrome 的 js 控制台中执行时的行为感到惊讶:

var me = { name: 'John'};

function theFunc(){
console.log(this);
}

theFunc.bind(me);

theFunc();//this is window???

我期待绑定(bind)函数调用绑定(bind)到对象文字...

最佳答案

您需要像这样调用(将其分配给变量)函数

theFunc = theFunc.bind(me);

theFunc();

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

.bind

Example

附注在我们的例子中,您还可以使用 callapply,如下所示

var me = { name: 'John'};

function theFunc(){
console.log(this);
}

// theFunc.call(me); or

theFunc.apply(me);

Example

关于javascript - javascript 函数的绑定(bind)方法存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27923247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com