js中this的理解()-js
js中this的理解()
1、函数被当作函数使用(调用)时,函数的可以说是没有this的,因为这个this就是window。 当 f() 调用时,就相当于window.f(),所以this指向window。无论是在任何地方调用函数!(除apply, bind, call方式外)
2、函数被当作构造函数用时,this指向new返回的实例对象。
3、this不能离开对象实例,离开对象实例谈this都是无意义的。
function f() {
const obj = {
name: 'obj',
aa() {
console.log('bb this: '+this.name);
const bb = () => {
console.log(this.toString());
}
bb()
let val = 'haha'
console.log('cc this: '+this.name);
const cc = function() {
console.log(this.toString())
console.log(val);
}
cc()
}
}
obj.aa()
}
f()
————————
1、函数被当作函数使用(调用)时,函数的可以说是没有this的,因为这个this就是window。 当 f() 调用时,就相当于window.f(),所以this指向window。无论是在任何地方调用函数!(除apply, bind, call方式外)
2、函数被当作构造函数用时,this指向new返回的实例对象。
3、this不能离开对象实例,离开对象实例谈this都是无意义的。
function f() {
const obj = {
name: 'obj',
aa() {
console.log('bb this: '+this.name);
const bb = () => {
console.log(this.toString());
}
bb()
let val = 'haha'
console.log('cc this: '+this.name);
const cc = function() {
console.log(this.toString())
console.log(val);
}
cc()
}
}
obj.aa()
}
f()