Arrow function in this

First, know what is the function of the arrow, the arrow key function is no function, but a similar function arrow:

var a = ()=>{

  return 1;

}

Equivalent to

function a(){

  return 1;

}

Then look at their differences:

 

Normal function of this:

1. this always represents its direct caller, for example obj.function, then the function of this is to obj;

2. In the default (non-strict mode, unused 'use strict'), did not find direct caller, then this refers to the window;

3. In strict mode, there is no direct function in this caller is undefined;

4. Use call, apply, bind (ES5 new) binding, this refers to the bound object.

 

Arrow function in this:

1. Arrow function captures it in the context of this value, this value as its own, this value does not itself;

this 2. arrow always points to a function of the context of the this, any method can not change its point, such as call (), bind (), apply ().

 

1. anonymous functions as a function of the arrow, can not not be used as a new constructor

var B = ()=>{

  value:1;

}

var b = new B();

// error prompt: Uncaught TypeError: B is not a constructor

 

2. arrow function does not bind arguments, replacing it with rest parameters ... to solve

function A(a){

  console.log(arguments); //[object Arguments] {0: 1}

}

 

var B = (b)=>{

  console.log(arguments); //ReferenceError: arguments is not defined

}

 

var C = (... c) => {//...c rest parameter is the

  console.log(c); //[3]

}

A(1);

B(2);

C(3);

 

3.箭头函数会捕获其所在上下文的 this 值,作为自己的 this 值

var obj = {

  a: 10,

  b: function(){

    console.log(this.a); //10

  },

  c: function() {

     return ()=>{

           console.log(this.a); //10

     }

  }

}

obj.b();

obj.c()();

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

这句话是MDN里面写的,但是我觉得这条和上条其实是一条,还是捕获所在的上下文,比如下面这个例子:b是一个箭头函数,然后它的 this是指向window,这是为什么呢,因为箭头函数捕获的是obj{}这个对象的环境,然后这个环境的this指向的是window,就相当于上一条的例子:在c方法里面return的那个箭头函数捕获的是c:function(){}这个环境的this,而这个环境的this是obj,这样是不是就清晰明了了

var obj = {

  a: 10,

  b: () => {

    console.log(this.a); //undefined

    console.log(this); //window

  },

  c: function() {

    console.log(this.a); //10

    console.log(this); //obj{...}

  }

}

obj.b();

obj.c();

 

使用call()和apply()调用

通过 call() 或 apply() 方法调用一个函数时,只是传入了参数而已,对 this并没有什么影响

var obj = {

  a: 10,

  b: function(n){

    var f = (v) => v + this.a;

    return f(n);

  },

  c: function(n) {

    var f = (v) => v + this.a;

    var m = {a:20};

    return f.call(m,n);

  }

}

console.log(obj.b(1)); //11

console.log(obj.c(1)); //11

 

箭头函数没有原型属性

var a = ()=>{

  return 1;

}

function b(){

  return 2;

}

 

console.log(a.prototype);//undefined

console.log(b.prototype);//object{...}

 

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

箭头函数不能换行

var a = ()

=>1; //SyntaxError: Unexpected token =>

 

 

Guess you like

Origin www.cnblogs.com/ranyonsue/p/11867514.html