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指向
apply 、 call 和bind 允许切换函数执行的上下文环境(context),即 this 绑定的对象,可以将 this 引用到任何对象。它们的区别主要是在于方法的实现形式和参数传递上的不同。
- 函数.call(对象,arg1,arg2…)
- 函数.apply(对象,[arg1,arg2,…])
- 函数.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
文中若有错误的地方希望指出,共同进步。
感谢观看,希望对你有所帮助!