javascript Array.from问题

function myfunc(n){
            return n+2;
        }

let obj = {
            myfunc: function(n) {
                return n+5;
            }
        }
//这里的this是全局作用域对象window
console.log(Array.from([1,2,3,4],x => this.myfunc(x)));
//这里通过Array.from()的第三个参数把this指向改为obj
console.log(Array.from([1,2,3,4],x => this.myfunc(x),obj));

期望输出:
3,4,5,6
6,7,8,9

实际输出
3,4,5,6
3,4,5,6

为什么会出现这个情况呢,我想通过Array.from的第三个参数更改this不成功,怎么解决这个问题呢,谢谢啦

阅读 1.4k
2 个回答

箭头函数造成的吧,箭头函数的this比较特殊,不能修改

image.png

虽然不是很肯定,但我猜是箭头函数的影响,试试这样写:

console.log(Array.from([1,2,3,4], function (x) { return this.myfunc(x) }, obj))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题