箭头函数的this在定义时就被确定了,箭头函数没有自己的 this 值,箭头函数中所使用的 this 都是来自函数作用域链,箭头函数中的this从上层作用域寻找。
apply无法改变箭头函数的this指向
由于对象是作为对象字面量的属性定义的,对象字面量在全局代码中定义,因此,箭头函数内部的this值与全局函数的this值相同
代码:
<script>
/*
对象类型转换
*/
var x = {
x: 1,
toString() { return x } // 指的是 x对象
};
var y = {
y: 1,
toString() { return this.y }
};
console.log(y == 1)
console.log(x.toString())
console.log(NaN === NaN) //false
console.log(NaN !== NaN) //true
console.log(true == 2) //false
console.log(true == '1') //true
console.log('[object Object]' == { x: '1' }) // true
console.log('1,2,3' == [1, 2, 3]) // true
console.log(Object.is(NaN, NaN)); //true
/*
this指向
*/
// https://blog.csdn.net/qq_36422171/article/details/115597314
// https://www.jb51.net/article/228798.htm
window.id = 0
const obj = {
id: 1,
b: () => {
console.log(this.id)
},
c: function () {
console.log(this.id)
}
}
class people {
constructor() {
this.id = '001'
}
d = () => {
console.log(this.id)
}
e() {
console.log(this.id)
}
}
// 在字面量中直接定义的箭头函数无法继承该对象的this,而是往外再找一层,就找到了window,
// 因为字面量对象无法形成自己的一层作用域,但是构造函数可以
obj.b() //0
obj.c() //1
var p = new people()
// console.log(p);
obj.fn1 = p.d
obj.fn2 = p.e
obj.fn1() //001
obj.fn2() //1