javascript this理解
先对this做几个说明(引自高级编程):
1、this 引用的是函数据以执行的环境对象
2、函数定义中的this会在代码执行过程中引用不同的对象:由于函数调用之前,this值并不确定
3、this 是函数内部属性
a.b() 这个时候 b里面的this是 a( ‘里面’ 指顺序代码快 )
b.apply(a) b里面的this是a
b.call(a) b里面的this是a
b() 这个时候 b里面的this 是window
例子1:
var myObject = {
foo:"bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
function aa(){
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}
//下面的调用方法,this=window 调用函数没有指定据以执行的环境,默认为window
aa();
//而下面的调用方法,则改变了this的指向
aa.call(this);
}
}
myObject.func();
例子2:
var name = "zhang"; function getName(){ console.log(this.name); } var obj = { name:"ling", getName:getName } getName();//zhang 直接调用,this=window getName.call(obj); //ling 使用call强行把getName内部的this指向obj //上面的这些,只是想要说明,this的指向,跟它的使用方法有关。 //跟这个函数,定义在哪个区域无关。 var age = 2; var MyAge = { age:1, getAge:function(){ console.log(this.age); } } var newAge = MyAge.getAge; MyAge.getAge(); //1 this指向MyAge newAge(); //2 this指向window newAge.call(MyAge); //1 this指向MyAge
例子3:
var fun = function() { alert(this.i); }; function outer() { this.i = 10; alert(this.i); }; var test = new outer(); test.fan = fun; test.fan();//this=outer
浙公网安备 33010602011771号