javascript this指向总结

javascript this指向总结

1.单独的this,指向的是window这个对象
alert(this) // this -> window

2.全局函数中的this
function demo() {
// ‘use strict’; 严格模式
alert(this); // this -> window
}
demo();
在严格模式下,this是undefined.

3.函数调用的时候,前面加上new关键字
所谓构造函数,就是通过这个函数生成一个新对象,这时,this就指向这个对象。
function demo() {
//alert(this); // this -> object
this.testStr = ‘this is a test’;
}
let a = new demo();
alert(a.testStr); // ‘this is a test’

4.用call与apply的方式调用函数
call 和 apply 的作用,完全一样,唯一的区别就是在参数上面。
call 接收的参数不固定,第一个参数是函数体内 this 的指向,第二个参数以下是依次传入的参数。
apply接收两个参数,第一个参数也是函数体内 this 的指向。第二个参数是一个集合对象(数组或者类数组)
/apply()方法/
function.apply(thisObj[, argArray])
/call()方法/
function.call(thisObj[, arg1[, arg2[, [,…argN]]]]);*

function demo() {
alert(this);
}
demo.call(‘abc’); // abc
demo.call(null); // this -> window
demo.call(undefined); // this -> window
改变 this 的指向(把 this 从 demo 指向到 abc )
方法借用( abc 只是借用 demo 方法)

5.定时器中的this,指向的是window
setTimeout(function() {
alert(this); // this -> window ,严格模式 也是指向window
},500)

6.元素绑定事件,事件触发后,执行的函数中的this,指向的是当前元素
window.onload = function() {
let $btn = document.getElementById(‘btn’);
$btn.onclick = function(){
alert(this); // this -> 当前触发
}
}

//jquery
$(’.btn’).click(function(){
alert(this); // this -> 当前触发
})

7.函数调用时如果绑定了bind,那么函数中的this指向了bind中绑定的元素
window.onload = function() {
let $btn = document.getElementById(‘btn’);
$btn.addEventListener(‘click’,function() {
alert(this); // window
}.bind(window))
}

8.对象中的方法,该方法被哪个对象调用了,那么方法中的this就指向该对象
let name = ‘finget’
let obj = {
name: ‘FinGet’,
getName: function() {
alert(this.name);
}
}
obj.getName(); // FinGet
let fn = obj.getName;
fn(); //finget this -> window

9.箭头函数调用
函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象!!!
由于箭头函数没有自己的this,所以当然也就不能用call()、apply()、bind()这些方法去改变this的指向
(function() {
return [
(() => this.x).bind({ x: ‘inner’ })()
];
}).call({ x: ‘outer’ });
// [‘outer’]

在箭头函数里面,没有 this ,箭头函数里面的 this 是继承外面的环境。
let obj={
a:222,
fn:function(){
setTimeout(()=>{console.log(this.a)});
}
};
obj.fn(); // 222
这次输出 222 是因为,传给 setTimeout 的是箭头函数,然后箭头函数里面没有 this ,所以要向上层作用域查找,在这个例子上, setTimeout 的上层作用域是 fn。而 fn 里面的 this 指向 obj ,所以 setTimeout 里面的箭头函数的 this ,指向 obj 。所以输出 222 。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值