ECMAScript-箭头函数

it2025-05-25  23

文章目录

一、ECMAScript-箭头函数1. this指向定义时所在的对象,而不是调用时所在的对象2. 不可以当作构造函数,不可以使用new 关键字调用,没有new.target,没有原型,没有super3. 不可以使用arguments对象4. 自动执行函数

一、ECMAScript-箭头函数

es5中的函数定义

// es5中定义函数 // 方式一 function sum(x, y) { return x + y } // 方式二 var sum = function sum(x, y) { return x + y } console.log(sum(4, 5)) // 这两种定义方式的区别 // 1. 方式一:定义的函数,无论你在函数前调用,还是函数后调用,都不会存在问题,因为存在函数预编译 // 2. 方式二:定义的函数,只是把函数赋值一个变量,在js中存在变量提升,如果在定义之前调用,会提示未定义,只能在函数后调用。

箭头函数定义:

// 箭头函数 let sum = (x, y) => { return x + y } console.log(sum(4, 5)) // 简写 let sum = (x, y) => x + y console.log(sum(4, 5)) let x = x => x // 等同于 let x = function(x) { return x }
1. this指向定义时所在的对象,而不是调用时所在的对象
let oBtn = document.querySelector('#btn') oBtn.addEventListener('click', function(){ console.log(this) // <button id="btn">确定</button> setTimeout(function(){ console.log(this) // Window {window: Window, self: Window, document: document, name: "", location: Location, …} 调用的window对象 }, 1000) // this怎么指向当前的对象,es5中有三种方式可以实现,bind,call,apply // 这边使用bind 因为call,apply都是立即执行 setTimeout(function(){ console.log(this) // <button id="btn">确定</button> }.bind(this), 1000) // 箭头函数 // 箭头函数里没有this,是继承外层函数的this,这边父层函数this指向是<button id="btn">确定</button> setTimeout(() => { console.log(this) // <button id="btn">确定</button> }, 1000) })
2. 不可以当作构造函数,不可以使用new 关键字调用,没有new.target,没有原型,没有super
// es5中定义一个类 function People(name, age){ console.log(this) // People {} this.name = name this.age = age } var p1 = new People('zhangsan','18') console.log(p1) // People {name: "zhangsan", age: "18"} // 箭头函数定义不可以当作构造函数 let People = (name, age) => { this.name = name this.age = age } let p2 = new People('zhangsan','18') // 编译报错:People is not a constructor console.log(p2)
3. 不可以使用arguments对象
// 正常函数 let foo = function(){ console.log(arguments) } foo(1, 2, 3) // 箭头函数 let foo = () => { console.log(arguments) } foo(1, 2, 3) // 编译报错:arguments is not defined // rest方式 let foo = (...args) => { console.log(args) // [1, 2, 3] } foo(1, 2, 3)
4. 自动执行函数
// es5中自动执行函数 (function(){ console.log(2) })() // 或者 (function(){ console.log(3) }()) // 箭头函数 (()=>{ console.log(4) })() // 报错 (()=>{ console.log(5) }()) // 编译报错:Unexpected token, expected ","
最新回复(0)