做为一个后端开发人员,前端虽然没有那么专业,但js肯定是不能不会的。而js中的this关键字又很有意思。
其实我们没法确定的说this就一定指向谁。在不同的情况下会有不同的指向。
1.首先在全局作用域或者普通函数中this指向全局对象window。
//直接打印
console.log(this); //window
//function声明函数
function test(){
console.log(this);
}
test(); //window
//function声明函数赋给变量
var test= function(){
console.log(this);
}
test(); //window
2.作为方法来调用时,谁调用该方法就指向谁。
//对象方法调用
var obj = {
test: function () {
console.log(this);
}
}
obj.test(); //obj
//事件绑定
var btn = document.getElementById("button");
btn.onclick = function () {
console.log(this) // btn
}
//jquery的ajax
$.ajax({
self: this,
type:"get",
url: url,
async:true,
success: function (res) {
console.log(this) // this指向$.ajxa()括号中包裹的对象
console.log(self) // window
}
});
3.在构造函数或者构造函数原型对象中this指向构造函数的实例
//使用new实例化对象
function test (name) {
this.name = name;
console.log(this); //people
self = this
}
var obj = new test('yoyo');