我该如何解决“这个”?

问题描述 投票:0回答:1

target = 'global honey';

const test = () => {
    console.log(this.target); // global honey
}

const object = {
    target: 'local honey',
    action: test
}

object.action();

此代码的输出未定义。我想输出全局honey,但是用bind不能解决这个问题吗?

target = "global honey";

const test = () => {
  console.log(this.target); // global honey
};

const object = {
  target: "local honey",
  action: test,
};

object.action.bind(object);

当我运行此代码时,没有输出任何值。

javascript this bind
1个回答
0
投票

当我运行此代码时,没有输出任何值。

看起来您假设

.bind()
将运行您的函数,但事实并非如此。它只是返回一个新函数。

其次,

bind
对箭头功能没有影响,所以在这里调用它是没有用的。

我要输出全球蜂蜜

那么你的代码中“本地蜂蜜”的用途是什么?我假设你实际上想输出“本地蜂蜜”...

在这种情况下,您不需要绑定,但应该将

test
设为
function
,以便它将
this
初始化为调用它的对象,而不是其词法上下文中的
this
(这是
globalThis
)。

所以:

target = 'global honey';

function test() {
    console.log(this.target); // local honey
}

const object = {
    target: 'local honey',
    action: test
}

object.action();

© www.soinside.com 2019 - 2024. All rights reserved.