您的位置:首页 > Web前端 > JavaScript

javaScript中普通函数和箭头函数说的区别

2019-02-05 14:12 465 查看

先通过代码查看两者的区别

//箭头函数
var fun = () => {
console.log('hello');
}
//普通函数
function (fun) {
console.log('hello');
}

可以看出箭头函数省略了function的声明 通过箭头来表示 那么二者的区别就仅限于此吗?

如果是像当初的我一样简单的考虑固定住 this 这个易变的家伙……那倒是很简单,有些常用的方法,比如这样:

function fun () {
var _this = this;
return function () {
console.log(_this);
}
}

或者

function fun () {
return function () {
console.log(this);
}.bind(this);
}

为了实现类似的效果,我们只有重新定义一个局部变量这一种方式来固定住我们想要的this。下面我们看用箭头函数的声明方式。

function fun () {
return ()=>{
console.log(this);
}
}

var obj = {
a: 10,
b: () => {
console.log(this.a); // undefined
console.log(this); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
},
c: function() {
console.log(this.a); // 10
console.log(this); // {a: 10, b: ƒ, c: ƒ}
}
}
obj.b();
obj.c();

箭头函数不绑定this,会捕获其所在的上下文的this值,作为自己的this值来使用 并且箭头函数通过 call() 或 apply() 方法调用一个函数时,只传入了一个参数,对 this 并没有影响。

let obj2 = {
a: 10,
b: function(n) {
let f = (n) => n + this.a;
return f(n);
},
c: function(n) {
let f = (n) => n + this.a;
let m = {
a: 20
};
return f.call(m,n);
}
};
console.log(obj2.b(1));  // 11
console.log(obj2.c(1)); // 11

箭头函数没有原型属性

var a = ()=>{
return 1;
}

function b(){
return 2;
}

console.log(a.prototype);  // undefined
console.log(b.prototype);   // {constructor: ƒ}

箭头函数不能当做Generator函数,不能使用yield关键字

总结

箭头函数的 this 永远指向其上下文的 this ,任何方法都改变不了其指向,如 call() , bind() , apply()
普通函数的this指向调用它的那个对象

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: