-
this
对象是在运行函数时基于函数的运行环境绑定的;全局环境中,this
对象就是window
,而当函数被作为某个对象的方法调用时,this
就是那个对象(例如全局调用,函数就作为window
的方法)
- 在理解
this
对象前先统一下函数调用的写法func.call(context,p1,p2)
,this
就是这个context
function funcAdd(a,b){
console.log(a+b);
}
funcAdd.call(undefined,1,2); //3
//浏览器的规则是如果你传的context是null或者undefined,那么window对象就是默认的context严格模式下默认 context是undefined),此时可简写为funcAdd.call(1,2);
var obj = {
name: "Asher",
age: 3,
show: function(){
console.log( this.name + ":" + this.age )
}
};
obj.show.call(obj); //Asher:3 这里的this就是obj对象
var john = {
firstName: "John"
}
function func() {
alert(this.firstName + ": hi!");
}
john.sayHi = func; //相当于给对象john添加了func方法
john.sayHi(); //弹出对话框 John:hi!,该语句相当于john.sayHi.call(john);john是当前的this
func(); ////弹出window,全局调用;相当于func.call();
function func() {
alert(this);
}
function fn0(){
function fn(){
console.log(this);
}
fn();
}
fn0(); //window;fn()是全局调用
document.addEventListener('click', function(e){
console.log(this); //document,事件绑定时触发的DOM对象指向this
setTimeout(function(){
console.log(this); //window;全局调用
}, 200);
}, false);
var john = {
firstName: "John";
}
function func() {
alert( this.firstName );
}
func.call(john); //弹出John,这里指定了john就是this
var john = {
firstName: "John",
surname: "Smith"
}
function func(a, b) {
alert( this[a] + ' ' + this[b] );
}
func.call(john, 'firstName', 'surname');
//弹出John Smith
//指定this和调用的对象为john,'firstName', 'surname'为传给func的实参
var $btn = $('.btn');
var module= {
bind: function(){
$btn.on('click', function(){
console.log(this); //当$btn发生点击事件时,this指向$btn这个DO对象
this.showMsg();
})
},
showMsg: function(){
console.log('饥人谷');
}
}
//修改后:
var $btn = $('.btn');
var module= {
bind: function(){
var $this = this;
$btn.on('click', function(){
console.log(this);
$this.showMsg();
})
},
showMsg: function(){
console.log('饥人谷');
}
}
var obj = {
foo: function(){
console.log(this)
}
}
var bar = obj.foo;
obj.foo(); //输出obj;相当于obj.foo.call(obj);this就是obj
bar(); // 输出window;没有指定context,那么默认为undefined即window
function fn (){ console.log(this) }
function fn2(){}
var arr = [fn, fn2];
arr[0](); //输出arr
//这里的arr[0]可以理解为arr.0,所以转换为arr.0.call(arr);