Skip to content

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

Open

Description

@chenfan0
  • 箭头函数没有自己的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)  // 返回一个类数组对象,该对象保存着参数。

Activity

  1. changed the title [-]js面试题:箭头函数和普通函数的区别?[/-] [+]JS:箭头函数和普通函数的区别?[/+] on Jun 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    JSjavascript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions