var person = {
say: function () {},
say2: () => {}
}
console.dir(person.say)
console.dir(person.say2)
prototype
和arguments
属性的this
的指向不同this
是在函数运行时候确定的, 基本满足谁调用指向谁, 特殊情况除外this
是在函数定义就确定了, 因为箭头函数是没有this
, 所以内层的this
就指向箭头函数上层的作用域, 并且不可以通过call, apply, bind
改变this
指向var aaaa = '大火车'
var person = {
aaaa: '小火车',
say: function () {
console.log(this.aaaa)
},
say2: () => {
console.log(this.aaaa)
}
}
person.say() // 小火车
person.say2() // 大火车
普通函数say
中的this
因为是被person
对象调用, 所以this
就指向了person
对象, 打印的结果就是小火车
箭头函数say2
中的this
是在函数定义的时候就确定了, 而且对象不构成独立的作用域, 所以this
就指向了顶级作用域window
, 打印结果就是大火车
function Person() {
}
const per = new Person()
使用new
创建构造函数的四个步骤
this
指向// 1.创建一个空对象
let obj = {}
// 2.将对象的对象原型赋予Person的原型对象
obj.__proto__ = Person.prototype
// 3.改变this指向
let result = Person.call(obj, ...arguments)
// 4. 返回新的对象
return result
因为箭头函数是没有prototype
原型对象的, 因此如果直接使用new
就会报错
arguments
const aa = ()=> {
console.log(arguments)
}
aa()
因为这里的箭头函数往上层作用域查找arguments
, 但是全局的作用域window
是没有arguments
属性的, 所以报错
function aa() {
const bb = ()=> {
console.log(arguments)
}
bb()
}
aa() // Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
这里的箭头函数会找到上层作用域aa
函数的arguments