时间:2021-07-01 10:21:17 帮助过:22人阅读
我常常的使用箭头函数,却还没有对箭头函数有个深入的了解,现在找一下这2个函数的不同点
由于箭头函数没有原型,因此箭头函数本身没有this
let a = () => {}
console.log(a.prototype) // undefined
let b = function () {}
console.log(b.prototype) // Objectlet a;
let barObj = {
    msg: 'bar的this指向'
}
let fooObj = {
    msg: 'foo的this指向'
}
bar.call(barObj)
foo.call(fooObj) // { msg: 'bar的this指向'  }
bar.call(fooObj)
a() // { msg: 'foo的this指向' }
function foo() {
    a()
}
function bar () {
    a = () => {
        console.log(this)
    }
}从上面例子中可以得出:
箭头函数的this指向定义时所在的外层第一个普通函数,跟使用位置没有没有关系被继承的普通函数的this指向改变,箭头函数的this也会跟着改变。
不能直接修改箭头函数的this
可以通过修改被继承的普通函数的this指向,然后箭头函数的this也会跟着改变
3. 箭头函数使用arguments
let b = () => {
        console.log(arguments);
    }
    b(1,2,3,4) // arguments is not defined
    function bar () {
        console.log(arguments);  // 完成第二个普通函数
        bb('完成第一个普通函数')
        function bb() {
            console.log(arguments); // 完成第一个普通函数
            let a = () => {
                console.log(arguments); // 完成第一个普通函数
            }
            a('箭头函数')
        }
    }
    bar('完成第二个普通函数')从上面可以得出以下2点
无论箭头函数的this指向哪里,使用new调用箭头函数都会报错,箭头函数没有构造函数
let a = () => {}
    let b = new a() // a is not a constructor【相关推荐:JavaScript视频教程】
以上就是JavaScript普通函数和箭头函数有什么区别?的详细内容,更多请关注Gxl网其它相关文章!