码迷,mamicode.com
首页 > 其他好文 > 详细

箭头函数和普通函数的区别

时间:2018-10-12 21:25:13      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:fine   UNC   ofo   ssi   oba   调用   http   argument   stat   

js箭头函数和普通函数的区别

1.不邦定this

在箭头函数出现之前,每个新定义的函数都有其自己的 this 值

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    return function(){
      console.log(this.value = this.value * 2); 
    }
  }
}

myObject.double()();  //希望value乘以2
myObject.getValue();  //1

在ECMAscript5中将this赋给一个变量来解决:

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    var that = this;
    return function(){
      console.log(that.value = that.value * 2); 
    }
  }
}

myObject.double()();  //2
myObject.getValue();  //2

除此之外,还可以使用 bind 函数,把期望的 this 值传递给 double() 函数。

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    return function(){
      console.log(this.value = this.value * 2); 
    }.bind(this)
  }
}

myObject.double()();  //2
myObject.getValue();  //2

箭头函数会捕获其所在上下文的 this 值,作为自己的 this 值,因此下面的代码将如期运行。

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    //回调里面的 `this` 变量就指向了期望的那个对象了
    return ()=>{
      console.log(this.value = this.value * 2); 
    }
  }
}

myObject.double()();  
myObject.getValue();  

2.使用call()和apply()调用

由于 this 已经在词法层面完成了绑定,通过 call() 或 apply() 方法调用一个函数时,只是传入了参数而已,对 this 并没有什么影响:

 var myObject = {
  value:1,
  add:function(a){
    var f = (v) => v + this.value;
    return f(a);
  },
  addThruCall:function(a){
    var f = (v) => v + this.value;
    var b = {value:2};
    return f.call(b,a);
    
  }
}

console.log(myObject.add(1));    //2
console.log(myObject.addThruCall(1));    //2

3.箭头函数不绑定arguments,取而代之用rest参数…解决

var foo = (...args) => {
  return args[0]
}

console.log(foo(1))    //1

4.使用new操作符

箭头函数不能用作构造器,和 new 一起用就会抛出错误。

var Foo = () => {};
var foo = new Foo();  //Foo is not a constructor

5.使用原型属性

箭头函数没有原型属性。

var foo = () => {};
console.log(foo.prototype) //undefined

6.不能简单返回对象字面量

var func = () => {  foo: 1  };
// Calling func() returns undefined!
var func = () => {  foo: function() {}  };
// SyntaxError: function statement requires a name
//如果要返回对象字面量,用括号包裹字面量
var func = () => ({ foo: 1 });

7.箭头函数当方法使用的时候没有定义this绑定

var obj = {
  value:1,
  add:() => console.log(this.value),
  double:function(){
    console.log(this.value * 2)
  }
}

obj.add();  //undefined
obj.double(); //2

8.箭头函数不能换行

var func = ()
           => 1; // SyntaxError: expected expression, got ‘=>‘

箭头函数和普通函数的区别

标签:fine   UNC   ofo   ssi   oba   调用   http   argument   stat   

原文地址:https://www.cnblogs.com/mengshi-web/p/9780131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!