<button id='btn'>按钮</button>
<script>
//在全局作用下 this一般指向window
//在严格模式下 this一般是undefined
//在函数作用域下
//在事件处理函数中,this一般指得是绑定事件的元素
btn.onclick = function(){
console.log(this);//btn
}
对象调用方法时,this一般指向当前对象
var obj = {
name:'孙悟空',
run :function(){
console.log(this == obj);//true
}
}
obj.run();
在普通函数中 this一般指向window
function fn(){
console.log(this);//window
}
fn()
在回调函数 this一般指向的也是window
var arr = [1,2,3];
arr.forEach((item,index)=>{
console.log(this);//window
})
定时器中也为window
setInterval(()=>{
console.log(this);//window
},666)
用call的方法
参数(新的指向,参数1,参数2);
function fn(x,y){
console.log(x,y,this);//1,2,'abc'
}
fn.call('abc',1,2)
var obj = {
name :'唐三',
run : function(){
console.log(this);//name:'唐浩',age:18
}
}
var newObj = {
name:'唐浩',
age:18
}
obj.run.call(newObj)
用apply的方法
参数(新的指向,[参数1,参数2])
function fn(x,y){
console.log(x,y,this)
}
fn(1,2);
fn.call(true,1,2);
fn.apply(true,[1,2])
</script>
js中this指向
于 2021-02-25 22:32:51 首次发布