ES6箭头函数和js普通函数的区别整理
普通函数的this指向为:谁调用它this就指向谁,this被不同对象调用是会变的
箭头函数的this指向为:声明该箭头函数时,外层第一个普通函数的this指向谁就固定为谁,不会改变
1 2 3 4 5 6 7 8 9 10 11 12 | function foo() { console.log( this ) } const obj = { a: 2, foo: function (){console.log( this )} } foo() //this指向为window obj.foo() //this指向为对象obj let foo2 = obj.foo foo2() //this指向为window |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | let foo = ()=> { console.log( this ) } const obj = { a: 2, foo: function () { return ()=>{console.log( this )} } } foo() //this指向window obj.foo()() //this指向对象obj let foo2 = obj.foo() foo2() //this指向对象obj |
1 2 3 4 5 6 7 8 9 10 11 | function foo() { console.log( this ) } new foo() //window let foo2 = ()=>{ console.log( this ) } new foo2() //报错 Uncaught TypeError: foo2 is not a constructor |
1 2 3 4 5 6 7 8 9 10 11 | function foo() { console.log(arguments) } foo(1,2,3) //[1,2,3] let foo2 = ()=>{ console.log(arguments) } foo2(1,2,3) // 报错 Uncaught ReferenceError: arguments is not defined |
我们可以使用展开符来获取参数
1 2 3 4 | let foo2 = (...arguments)=>{ console.log(arguments) } foo2(1,2,3) //[1,2,3] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | var a = 1 var obj={ a:2 } function foo() { console.log( this .a) } foo() //1 foo.call(obj) //2,输出obj.a let foo2 = ()=>{ console.log( this .a) } foo2() //1 foo2.call(obj) //1,仍然输出window.a |
1 2 3 4 5 6 7 8 9 | var a = ()=>{ return 1; } function b(){ return 2; } console.log(a.prototype); //undefined console.log(b.prototype); //object{...} |
点赞(0)