ES6中的箭头函数和普通函数有什么区别?

1、普通函数中的this总是指向调用它的那个对象,

   箭头函数没有自己的this,他的this永远指向其定义环境,任何方法都改变不了其指向,如call()、bind()、apply()。(正是因为它没有this,所以也就不能用作构造函数,也没有原型对象)

2、箭头函数不能当作构造函数,也就是说,不能使用new命令,否则会报错。

3、箭头函数不能使用yield命令,因此箭头函数不能用作genertor函数。

4、箭头函数没有原型属性。

5、箭头函数不能使用argumen对象,该对象在函数体内不存在。如果要用,可以用rest参数代替。

6、变量提升:由于js的内存机制,function的级别最高,而用箭头函数定义函数的时候,需要var(let、const)关键字,而var所定义的变量不能得到变量提升。故箭头函数一定要定义于调用之前。

this的指向问题?

1、普通函数中,this指向其函数的直接调用者;

2、箭头函数中,this指向其定义环境,任何方法都改变不了其指向,如call()、bind()等;

3、构造函数中,如果不使用new,则this指向window,如果使用new创建了一个实例,则this指向该实例。

//不使用new指向window

function Person(name){

    console.log(this)//  window

    this.name = name;

}

Person('inwe')

// 使用new

function  Person (name) {

    this.name = name

    console.log(this) // people

    self = this

}

    var people = new Peron('iwen')

    console.log(self === people) //true

//这里new改变了this指向,将this由window指向Peoson的实例对象people

4、window内置函数中,如setInterval,setTimeout等,其内部的this指向Window。

5、匿名函数的this指向Window。

6、apply()、call()、bind()可以改变this的指向

猜你喜欢

转载自www.cnblogs.com/jswzy/p/10117712.html