我们可以在Javascript中使用多个此绑定吗?

一个小例子

function speak(line){
  console.log(`The ${this.type} rabbit says '${line}' you ${this.type}`);
}

let whiteRabbit = {type: "white", speak, type: "asshole"};

whiteRabbit.speak("OH my dear" + " how you smell ");

输出意外

The asshole rabbit says 'OH my dear how you smell ' you asshole

为什么不归还白兔子?

评论
xi惜相命
xi惜相命
{
  type: "white",
  speak,
  type: "as***le", // <- overrides the `type` key. now it's not white but "as***le"
}

最终的对象是

{
  type: "as***le",
  speak: "somevalue of the speak var",
}

它与数组相同

var a = [1, 2, 5];
a[2] = 2; // overrides the value, doesn't add it.
a[1] = 3; // overrides the value, doesn't add it.

// [1, 3, 2]

Therefore - simply rename the property to type1 for example or use a stack of values.

点赞
评论