javascript - 从另一个函数调用的箭头函数中“this”的值
问题描述
我有两个对象
var dog1 = {
sound: "bark1!",
bark: () => {
console.log(this)
console.log(this.sound);
}
}
和
var dog2 = {
sound: "bark2!",
bark: function() {
console.log(this);
console.log(this.sound);
dog1.bark();
}
}
现在我知道,如果我调用,dog1.bark()
我的值this
将等于Window
object,因为this
箭头函数的值取决于词法范围。
但是,如果我调用dog2.bark()
并在调用时从其中dog1.bark()
调用,那么值不应该this
是 dog2 吗?既然箭头函数的词法范围是 dog2 的 bark 函数?或者我在这里错过了什么?
希望对此进行一些澄清。我注意到这个问题被标记为重复,但我不明白为什么从旧式函数调用对象仍然导致值this
等于window
解决方案
推荐阅读
- node.js - 如何在节点 Js 中使用相同的表单代码进行添加和更新?
- c# - 确定模型中哪个嵌套属性为空?
- javascript - 无法读取未定义的属性“类型”提交表单后出现此错误
- apache-spark-sql - 如何从 spark sql join 中选择第一行
- c++ - 这两个代码之间的区别(为什么我的数组占用了额外的空间,即使我给了它一个限制)
- react-native - 将数据保存在 Expo 应用程序中并通过 AWS Amplify 发送
- wordpress - Wordpress:如果有特殊模板和自定义字段,则显示页面
- c - 有没有办法限制整数数据类型的值范围
- java - JWTDecodeException(无效的 JSON 格式)
- python - 如何将模块用于具有多处理的“全局”变量?