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

借鉴: https://www.cnblogs.com/biubiuxixiya/p/8610594.html
阮一峰 http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html

主要区别在this指向问题

1、普通函数的this 指向调用它的那个对象,例如 obj.func ,那么func中的this就是obj
2、箭头函数不能作为构造函数,不能使用new,没有this,arguments箭头函数,箭头函数的this永远指向其上下文的 this ,任何方法都改变不了其指向,如 call() , bind() , apply()(或者说箭头函数中的this指向的是定义时的this,而不是执行时的this)

var name = "The Window";

var object = {
    name : "My Object",
    getNameFunc : function(){
            console.log(this.name); // My Object

         return function(){
           return this.name; // The Window
          };
    },
    b: () => {
           return this.name; // the window
       },
       c: function() {
           return () => {
              return this.name; //My Object
          }
       }
}

猜你喜欢

转载自blog.csdn.net/zhangjing0320/article/details/81589601