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

刚才写下面一段代码时发现bind中this在箭头函数和普通函数指向不一样:

        <div class="live">
            <input type="text" name="" id="liveInput" value="" />
            <div id="showSpace"></div>
        </div>

        <script type="text/javascript">
            $('#liveInput').bind('input propertychang', function(event) {
                let texts = this.value;
                console.log(this)
                $('#showSpace').html(texts) 
            })           
        </script>

当在箭头函数是this指向window,而普通函数this指向input,于是在网上查了一下区别。

箭头函数相当于匿名函数,并且简化了函数定义。

箭头函数是匿名函数,不能作为构造函数,不能使用new

箭头函数不绑定arguments,用...代替

function A(a){
  console.log(arguments);
}
A(1,2,3,4,5,8);  //  [1, 2, 3, 4, 5, 8, callee: ƒ, Symbol(Symbol.iterator): ƒ]


let B = (b)=>{
  console.log(arguments);
}
B(2,92,32,32);   // Uncaught ReferenceError: arguments is not defined


let C = (...c) => {
  console.log(c);
}
C(3,82,32,11323);  // [3, 82, 32, 11323]

箭头函数通过 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);
    },
    d: function(n) {
        let f = function(n){ return (n + this.a)}
        let m = {
            a: 20
        };
        return f.call(m,n);
    }
};
console.log(obj2.b(1));  // 11
console.log(obj2.c(1)); // 11
console.log(obj2.d(1)); // 21

箭头函数没有原型属性

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

function b(){
  return 2;
}

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

This的区别

普通函数的this直接调用者,箭头函数指向函数所处的对象

普通函数的this:

  //匿名函数定时器由于没有默认的宿主对象,所以默认this指向window
  var obj = {
    say: function () {
      setTimeout(function() {
        console.log(this)
      });
    }
  }
  obj.say();    // window{postMessage: ƒ, blur: ƒ, focus: ƒ, …}

箭头函数的this:

  //箭头函数在obj的作用域中,所以this指向obj
  var obj = {
    say: function () {
      setTimeout(() => {
        console.log(this)
      });
    }
  }
  obj.say(); // obj

来源:
1、 箭头函数与普通函数的区别
2、 ES6中箭头函数与普通函数this的区别

原文地址:https://www.cnblogs.com/gxw123/p/13373743.html