this指向问题
总结:
1.this指向在函数调用中 this指向window(非严格)
2.在对象调用函数中 this指向调用函数的对象
3.在构造函数中 this指向实例出来的对象
4.在call,apply,bind中this 指向第一个参数
5.箭头函数中的this指向这个函数对象的外层对象
代码如下:
// this-用于访问当前方法所属的对象
// 普通函数
let obj={
a:12,
fn(){
console.log(this);// obj
},
fn: function(){
console.log(this==obj)// true
},
// 箭头函数
fn: ()=>{
console.log(this==obj)// false
}
}
// 直接写和后填里面没有任何区别
obj.fn=function(){
console.log(this==obj); // true
};
// 指向调用它的对象
document.onclick=function(){
console.log(this==document);// true
}
obj.fn();
let _this;
// 函数的this跟定义无关的,跟调用有关
function show(){
conole.log(this);// window
_this=this;
}
// 1-直接调用--window||undefined
show();
// 当使用严格模式‘use strict’;// undefine
// 2.-挂载对象上,然后执行方法--对象
let arr=[1,2,3];
arr.fn=show;// arr
arr.fn();
//3-window
setTimeout(show,100);// 定时器本身属于window
// 4-构造函数(new) --当前构建出来的实例
new show();// show的实例
let date = new Date();
console.log(date instanceof Date);// true
let s = new show();
console,log(s=--_this);
// 5 -工具函数 call强制改变this值
show();// undefine
show.call(12); // 12 把this变成12
show.call('asdfasdf');
show.call(new Date());
show.call({a: 12});
let arr=[1,2,3];
arr.forEach=function(cb){
for(let i=0;i<this.length;i++){
cb(this[i]);
}
}
arr.forEach(function (item){
console.log(this,item);// window||undefine
});
- 注意:
对象之间的比较用==
数字之前的比较用===,同时比较数据类型和数值