简单讲解 js 中this指向问题
如何判断this 倒是是哪一个对象?
看 this 在哪?
-
1:全局
this===window
-
2:function函数 “谁触发执向谁?”
-
2.1 函数触发是不是
call apply bind
如何是,this===参数
-
2.2 看是不是new 触发的 是
this === new
实例的对象
注意:看一下函数return 是否为 [数组 对象 函数],如果是 那么 this 为 retrun 值 -
2.3 普通对象调用,在
this === 触发函数的对象
-
-
3:箭头函数
没有 this 没有 arguments
关键看: 箭头函数卸载哪里?- 1: 全局
this === window
- 2: function 函数方法中
this === function中this
- 1: 全局
代码举例
this.aa = 123;
function foo(params) {
console.log('foo=========');
console.log(this);
}
var obj = {
a:foo,
lt:()=>{
// A window
// B obj
console.log('-----------------------');
console.log(this);
}
}
obj.lt();
var obj1 = {
b:foo
}
// 函数的触发有几种方式
// 1: 对象调用方式
// window.foo()
// window.obj.a()
// // 2 new 关键字触发函数
// var P = new foo()
// 3: call aply bind 触发的函数
// foo.apply(obj)
// foo.call(obj1)
// foo.bind(window)()
// foo()
function bar(params) {
// 坑:不要看代码在哪里写的
// 看:怎么执行的
foo()
console.log('bar=======',this);
var tast = ()=>{
console.log('bar中 this ======',this);
}
tast()
}
// bar()
// 坑: 看 写在哪里
var tast = ()=>{
console.log('global========this',this);
}
// obj.tast = tast
// console.log(obj);
// obj.tast() // 验证:箭头函数中this,不看函数是怎么触发的只看函数写在哪里