developer-plus / interview

https://interview.developer-plus.org
MIT License
9 stars 1 forks source link

JS:箭头函数和普通函数的区别? #8

Open chenfan0 opened 2 years ago

chenfan0 commented 2 years ago

function foo() { const bar = () => { console.log(this); } // window bar() }

foo()

function foo() { const bar = () => { console.log(this); } // window bar.call({}) // 通过call调用bar这个箭头函数,可以看到this还是window }

foo()

function foo() { const bar = () => { console.log(this); } // {} bar() }

foo.call({}) // 这里通过call调用foo,将foo的this绑定为{},这样bar的this往上找就找到了foo的this,就是{}

- 箭头函数没有prototype,所以箭头函数不能够被new。
```js
const foo = () => {}

console.log(foo.prototype) // undefined
new foo() // TypeError: foo is not a constructor

function bar(x, y) { console.log(arguments); }

foo(1, 2) // Uncaught ReferenceError: arguments is not defined。注意在node中这里不会报错,但是返回的值不是我们想要的。 bar(1, 2) // 返回一个类数组对象,该对象保存着参数。