目录
一、箭头函数
1、基础语法
2、箭头函数简写
二、箭头函数的 this
1、全局函数下的 this
2、对象方法里面的 this
3、构造函数的this
4、call()、apply()、bind()调用时的 this
一、箭头函数
ES6中引入了箭头函数。箭头函数允许我们编写更短的函数。
//之前普通函数hello = function() {return "Hello World!";}
//使用箭头函数之后
hello = () => {return "Hello World!";}
1、基础语法
语法:() =>{} // ():函数 =>:必须的语法,指向代码块 {}:代码块
原js写法function sum(a,b){return a+b;}console.log(sum(1,2)); //3现es6写法const sum=(a,b)=>{return a+b;}let res=sum(1,2);console.log(res); //3
2、箭头函数简写
代码块只有一句话,省略{ }和return
const sum = (a,b)=> a+b;
let res = sum(1,2);
console.log(res); //3
只有一个参数时,小括号( )可省略
const sum=a=>a+3;
let res=sum(1);
console.log(res); //4
const sum=a=>{
return a+3;
}
let res=sum(1);
console.log(res); //4
二、箭头函数的 this
1、全局函数下的 this
普通函数 this 跟调用者有关
function global(){
console.log(this);//Window{window: Window, self: Window, document: document, name: "", location: Location,…}
}
global();
箭头函数的 this ,this是静态 ,根据上下文的 this
const global=()=>{
console.log(this);//Window{window: Window, self: Window, document: document, name: "", location: Location,…}
}
global();
2、对象方法里面的 this
如果函数作为对象的方法调用,this指向的是这个上级对象,即调用方法的对象。
const Person={
realname:'张三',age:19,
say:function(){
console.log(this);//{realname: "张三", age: 19, say: ƒ}
}
}
Person.say();//Person实例
对象箭头函数的 this
箭头函数不绑定this关键字,箭头函数中的this,指向的是函数定义位置的上下文this。
箭头函数中的this指向是它所定义(声明)的位置,可以简单理解成,定义箭头函数中的作用域的this指向谁,它就指向谁。
const Person={
realname:'张三',age:19,
say:()=>{
console.log(this);//Window{window: Window, self: Window, document: document, name: "", location: Location,…}
}
}
Person.say();//window
3、构造函数的this
构造函数的 this 就是当前示例,指向新创建的对象本身
箭头函数的 this 一旦定义了就不允许改变
function Person(realname,age){this.realname=realname;this.age=age;this.say=()=>{console.log(this);}this.say1=function(){console.log(this);}}const P1=new Person('张三',19);const P2=new Person('李四',20);P1.say(); //Person{realname: "张三", age: 19, say: ƒ, say1: ƒ}P2.say(); //Person{realname: "李四", age: 20, say: ƒ, say1: ƒ}P1.say.call(P2);//Person{realname: "张三", age: 19, say: ƒ, say1: ƒ}P1.say1.call(P2);//Person{realname: "李四", age: 20, say: ƒ, say1: ƒ}
4、call()、apply()、bind()调用时的 this
var name='小王',age=17;var Obj={name:'小猪',ObjAge:this.age,myfun:function(fn,t){console.log(this.name+'年龄'+this.age,'来自'+fn+'去往'+t);}}var db={name:'白马',age:20,}Obj.myfun.call(db,'成都','上海'); //白马年龄20 来自成都去往上海Obj.myfun.apply(db,['成都','上海']); //白马年龄20 来自成都去往上海Obj.myfun.bind(db,'成都','上海')(); //白马年龄20 来自成都去往上海Obj.myfun.bind(db,['成都','上海'])(); //白马年龄20 来自成都,上海去往undefined
三者都可以改变 this 的指向对象
call 的参数是直接放进去的,第二第三第 n 个参数全都用逗号分隔,直接放到后面 obj.myFun.call(db,'成都', ... ,'string' )。
apply 的所有参数都必须放在一个数组里面传进去obj.myFun.apply(db,['成都', ..., 'string' ])。
bind 除了返回是函数以外,它 的参数和 call 一样。
当然,三者的参数不限定是 string 类型,允许是各种类型,包括函数 、 object 等等