Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chenfan0 opened this issue Jun 6, 2022 · 0 comments
Open

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

chenfan0 opened this issue Jun 6, 2022 · 0 comments
Labels
JS javascript

Comments

@chenfan0
Copy link
Member

chenfan0 commented Jun 6, 2022

  • 箭头函数没有自己的this,它的this是上一层作用域的this。如果直接对箭头函数使用call,bind,apply是不能够改变箭头函数的this的值。如果想要改变箭头函数的this,那么需要改变它上一层作用域的this。
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。
const foo = () => {}

console.log(foo.prototype) // undefined
new foo() // TypeError: foo is not a constructor
  • 箭头函数中没有argument参数
const foo = (x, y) => {
  console.log(arguments)
}

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

foo(1, 2)  // Uncaught ReferenceError: arguments is not defined。注意在node中这里不会报错,但是返回的值不是我们想要的。
bar(1, 2)  // 返回一个类数组对象,该对象保存着参数。
@chenfan0 chenfan0 added today 每日一题。 JS javascript labels Jun 6, 2022
@Hongbusi Hongbusi removed the today 每日一题。 label Jun 9, 2022
@Hongbusi Hongbusi changed the title js面试题:箭头函数和普通函数的区别? JS:箭头函数和普通函数的区别? Jun 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JS javascript
Development

No branches or pull requests

2 participants