ES6-箭头函数

210 阅读2分钟

this指向

箭头函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象,箭头函数中没有自己的this的,而箭头函数会默认使用父级的this。而普通的this:总是代表它的直接调用者,没找到直接调用者,则this指的是 window(匿名函数,定时器中的函数,由于没有默认的宿主对象,所以默认this指向window)。

    var obj = {
      name:"nwd",
      say: ()=> {
        console.log(this)
      }
    }
    obj.say();//Window

注:say方法中的this因为在箭头函数中,所以指向父作用域中,父作用域就是最外层作用域,父作用域中的this指向window,所以输出window。

    var obj = {
      name:"nwd",
      say: function() {
         setTimeout(()=>{
            console.log(this)
         })
      }
    }
    obj.say();//{name: "nwd", say: ƒ}

注:这个例子中,定时器箭头函数中的this指向外部作用域,即指向say方法中,say方法中this指向obj对象,所以输出person1对象。

    var obj = {
      name:"nwd",
      say: ()=> {
        setTimeout(()=>{
            console.log(this)
         })
      }
    }
    obj.say();//Window

注:定时器箭头函数中的this向上say方法中的this,但由于say方法中也是箭头函数,所以say方法中的this还要继续向上找,即找到了最外层,所以最后指向window。

总结:箭头函数中this,首先到它的父作用域找,如果父作用域还是箭头函数,那么接着向上找,直到找到我们要的this指向。

箭头函数不绑定arguments

我们知道在函数中,可以通过 arguments 关键字来获取到当前函数中传入的参数,但是在箭头函数中是没有这个关键字的

const fn = () => { console.log(arguments) }
fn()
//Uncaught ReferenceError: arguments is not defined

           function foo() {
    		var f = (i) => {
    			console.log(arguments)
    			return arguments[0] + i
                        //arguments[0]等于1

    		}
	        return f(2);
	    }
	    console.log(foo(1)); // 3

ES5:

                
                function foo() {
    		    var f = function(i) {
    			console.log(arguments)
    			return arguments[0] + i
                        //arguments[0]等于2

    		    }
		    return f(2);
		}
		console.log(foo(1));//4

注意:在使用箭头函数时,arguments 指向的对象并不是当前函数所属的argments,而是上级函数的arguments,所以需要将箭头函数转为function。这一点与箭头函数中的this相像。

箭头函数没有prototype属性

        
        var Person = function() {
    	}
    	console.log(Person.prototype)
    	//{constructor: ƒ}

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

箭头函数不能用于构造函数

        var Person = function(name) {
    		this.name = name;
    	}
    	var p1 = new Person("nwd")
    	console.log(p1.name)// "nwd"

        var Person = (name) => {
    		this.name = name
    	}
    	var p1 = new Person("nwd")
    	console.log(p1) //Person is not a constructor