JS中this的指向问题

1. 全局作用域或者普通函数中的this指向window对象(表示浏览器窗口),定时器里的this也指向的是window

console.log(this);//window
function fun1(params) {
    console.log(this);//window
}
fun1();//相当于window.fun1();

setTimeout(function () {
    console.log(this);//window
},1000);
//相当于
window.setTimeout(function () {
    console.log(this);//window
},1000); 

2. 方法(对象中的函数调用叫方法调用)调用中谁调用指向谁

var stu = {
    sayHi:function(){
        console.log(this);//this指向stu这个对象
    }
}
console.log(stu.sayHi());

在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素
HTML:

......
<body>
	<button>点我</button>
</body>
......

JS:


var btn = document.querySelector('button');
btn.onclick = function () {
    btn.innerHTML = 'hi';
    console.log(this);//指向<button>hi</button>
}

3. 构造函数中this指向构造函数实例

function Peo(name,age,sex) {
    this.name=name;
    this.age=age;
    this.sex = sex;
    console.log(this);//this指向peo1实例对象   Peo {name: 'mandy', age: 25, sex: '女'}
    this.habbies =function (songs,dances) {
        // console.log("habbies:"+songs+"\t"+dances);
    }
var peo1 = new Peo('mandy',25,'女');

4. 更改this指向
applycallbind 允许切换函数执行的上下文环境(context),即 this 绑定的对象,可以将 this 引用到任何对象。它们的区别主要是在于方法的实现形式和参数传递上的不同。

  1. 函数.call(对象,arg1,arg2…)
  2. 函数.apply(对象,[arg1,arg2,…])
  3. 函数.bind(对象,arg1,arg2,…)()
    注:bind返回的是一个函数体,并不会直接执行函数
function show(sex,num) {
    console.log("姓名:"+this.name+"\t年龄:"+this.age+"\t性别:"+sex+"\t电话:"+num);
}
var person = {
    name:'mandy',
    age:12
}
//使this指向person
show.call(person,'女',2466);//姓名:mandy	年龄:12	性别:女	电话:2466 
show.apply(person,['男',12345]);//姓名:mandy	年龄:12	性别:男	电话:12345
show.bind(person,'男',2476)();//姓名:mandy	年龄:12	性别:男	电话:2476

文中若有错误的地方希望指出,共同进步。
感谢观看,希望对你有所帮助!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值