面向对象语言中 this 表示当前对象的一个引用。
但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。
- 在方法中,this 表示该方法所属的对象。
setInterval(function () {
console.log(this);
}, 1000)
- 如果单独使用,this 表示全局对象。
function test() {
console.log(this);
}
test()
- 在函数中,this 表示全局对象。
function Person() {
console.log(this);
this.sayHello = function () {
console.log(this);
}
}
var p0 = new Person()
p0.sayHello()
- 原型对象中的this,指向当前对象
Person.prototype.Eat = function () {
console.log(this);
}
p0.Eat()
- 在事件中,this 表示接收事件的元素。
document.getElementsByClassName("div0")[0].onclick = function () {
// 此时this指的是绑定该事件的元素,比如此处this指的就是class="div0"的div元素
console.log(this);
}
call()、apply()和bind()的作用和区别
作用:改变函数运行时this的指向
区别:call():传入两个参数,第一个参数是this的指向,第二个是指传入的参数列表
function fun(a, b) {
console.log(this);
console.log(a, b);
}
var person = {
uname: "王五"
}
fun.call(person, 1, 2)
fun(1, 2)
apply():传入两个参数,第一个参数是this的指向,第二个是指传入的参数(数组的形式)
fun.apply(person, [1, 2])
fun(1, 2)
bind()传入两个参数,第一个参数是this的指向,第二个参数是传入的参数列表,使用bind()改变this指向后,原函数不会立刻执行,会返回一个新的函数
var result = fun.bind(person, 1, 2)
console.log(result);
call()和apply()函数是改变thishi后原函数立刻执行