1.this指向性
function的this指向性不是固定的,它随着调用环境的改变而改变。
function Student(name,age){
this.name=name
this.age=age
}
show();
function show(){
console.log(this)//window
}
此时调用show方法this指向的是window;若我们在页面中添加一个按钮标签,并将show方法绑定到该元素的点击事件上,此时的this指向就会发生改变;如果将该方法作为对象的属性值,this又会指向该对象,代码如下:
function Student(name,age){
this.name=name
this.age=age
}
show();//window
bt1.onclick=show;
function show(){
console.log(this)//<button id="bt1">确定</button>
}
let obj={
name:"wangyi",
show:show
}
obj.show()//指向该对象
可见,function定义的函数的this指向是由调用环境决定的。而箭头函数的this指向永远是定义时的环境。如下:
let show=()=>{
console.log(this)
}
show()//window
bt1.onclick=show;//window
let obj={
name:"wangyi",
show:show
}
obj.show();//window
2.function定义的函数有默认提升功能,而箭头函数没有
show()//window
function show(){
console.log(this);
}
这样写并不会报错
show()// Cannot access 'show' before initialization
let show=()=>{
console.log(this);
}
而箭头函数必须在定义以后再使用否则会报错。
3.function可以定义构造函数,但箭头函数不行,因为箭头函数的this指向性一旦定义了就是确定的无法改变。
function Student(name,age){
this.name=name;
this.age=age;
}
let s1=new Student(123,123)
console.log(s1.name);//123
而箭头函数会报错,报错提示该方法不是构造函数
let Student=(name,age)=>{
this.name=name;
this.age=age;
}
let s1=new Student(123,123)
console.log(s1.name);// Student is not a constructor
4.function函数具有argument参数(实参)集合,箭头函数没有,有的是rest参数。
//编写一个函数 计算n个数字的和 ,用户传入多少,就计算多少
function sum(a,b,c){
//arguments集合
console.log(arguments) //实参的集合:Arguments(10) [1, 2, 3, 4, 5, 6, 7, 9, 10, 12, callee: ƒ, Symbol(Symbol.iterator): ƒ]
let s=0
for(let n=0;n<arguments.length;n++){
s+=n
}
return s
}
console.log(sum(1,2,3,4,5,6,7,9,10,12))//45
let show=(a,b,...args)=>{
console.log(args)
}
show(1,2,3,4)//(2) [3, 4]与argument不同输出的是数组而不是集合,并且是抛除前两个参数的
以上