javascript - 理解 Javascript 中的 this 关键字

标签 javascript

我正在尝试打印下面的 Javascript 代码,它在第一行显示 true ,在第二行显示 false 。尽管它们看起来一样,但我不明白它们的区别

var someObj = {
  data: function() {
    console.log(this == someObj) // true
    console.log("Value of this " + this == someObj) //false
  }
};

someObj.data();

最佳答案

+ 将字符串连接到对象的 toString,以便您进行比较:

("Value of this " + this) == someObj

而不是

"Value of this " + (this == someObj)

var someObj = {
  data: function() {
    console.log(this == someObj) // true
    console.log("Value of this " + this == someObj) // false
    console.log("Value of this " + (this == someObj)) // true
  }
};

someObj.data();

关于javascript - 理解 Javascript 中的 this 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48353289/

相关文章:

javascript - 如何在一行中编写字段警报?

javascript - 在ajax中调用PHP函数,不推荐使用同步XMLHttpRequest

javascript - PHP 将值从一种形式转换为另一种形式

javascript - 通过 cypress.get() 选择 HTML 中的元素

javascript - 我如何从匿名自调用函数中公开函数?

javascript - 全屏功能无法正常工作

javascript - chrome.runtime.onMessage 中的 sendResponse 不起作用

javascript - 网页即将关闭(可能)事件?

javascript - 使用 javascript 检查 URL 是否包含值

javascript - 在 Chrome 中按比例调整图像大小