箭头函数:什么是箭头函数认识箭头函数
const add = (x, y) => { return x + y; }; console.log(add(1, 1)); 箭头函数的结构const/let 函数名=(参数 1,…)=>函数体;如何将一般函数改写成箭头函数
//声明形式 function add() {}
// 声明形式->函数表达式形式
const add = function () {};
// 函数表达式形式->箭头函数
const add = () => {};
箭头函数的注意事项:a.单个参数b.无参数或多个参数不能省略圆括号c.单行函数体=>单行函数体可以同时省略 {} 和 returnd.单行对象 =>如果箭头函数返回单行对象,可以在 {} 外面加上 (),让浏览器不再认为那是函数体 的花括号
// 单个参数可以省略圆括号 const add = x => { return x + 1; }; console.log(add(1));
const add = () => {//无参数的时候 括号不能省略 return 1 + 1; };
const add1 = (x, y) => {//多个参数的时候,括号不能省略 return x + y; }; console.log(add1(1, 1));
const add = (x, y) => { return x + y; }; //简写形式 const add=(x,y)=>x+y console.log(add(1,4));//5
//多行函数体不能再化简了 const add = (x, y) => { const sum = x + y; return sum; };
const add=(x,y)=>{ return{ sum:x+y } } //简写形式: 在{}外面加上(),让浏览器不再认为那是函数体的花括号 const add = (x, y) => ({ value: x + y });
非箭头函数中的 this 指向
全局作用域中的this指向:window对象console.log(this);//全局作用域中的this指向window对象
一般函数中的this指向:调用的使用才能确定指向谁? 作为函数调用指向window对象,作为方法被调用的时候,指向调用方法的对象
‘use strict’;
function add(){
//严格模式下 this指向undefined
//非严格模式下指向的是 window对象
console.log(this); }
add();//作为函数被调用的使用
‘use strict’;
const person={
name:‘zhangsan’,
add:add
}
function add(){
//作为方法被调用的时候,this 指向的是person对象
console.log(this)
}
//作为方法被调用的时候,this 指向的是person对象
person.add();
构造函数中的this的指向
//构造函数中的this指向的值构造函数内部创建的this
function createPerson(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex; }
函数的call(),apply()方法中的this指向
const obj={ name:‘xiaoming’ }
function fun1(){ console.log(this); } fun1.call(obj);//函数对象的call 函数中this指向的是call()传入的对象
fun1.apply(obj);//函数对象的apply 函数中的this指向的是apply()传入的对象
箭头函数中的 this 指向
箭头函数没有自己的 this
const person = { //箭头函数 speak: () => { console.log(this); } };
person.speak(); // window //如果是普通的函数,这里this指向的是person对象
看下面的场景说出this的指向
‘use strict’;
const person={
name:“zhangsan”,
playGame:function(){
const test=()=>{ console.log(this)
} test(); }
}
person.playGame();//this->person
const play=person.playGame;
play();//严格模式下this->undifined 非严格模式this->window
不适用箭头函数的场景
在构造函数中,箭头函数不适用(箭头函数没有自己的this) 需要this指向调用对象的时
document.getElementById(“btn”).addEventListener(‘click’,function(){ this.style.color=red; })
//下面的这个this指向就不是btn这个DOM对象,此时这么写就会报错 document.getElementById(“btn”).addEventListener(‘click’,()=>{ this.style.color=red; })
需要使用arguments的时候
function fun3(){
//这里的arguments接收到的就是所有的参数
console.log(arguments); }
fun3();
fun3(1,2,4);
const add=()=>{
// console.log(arguments);
// 箭头函数中没有arguments
}
add();
箭头函数简单的用法
最新推荐文章于 2025-01-15 01:06:54 发布