JavaScript中的this关键字

来源:互联网 发布:js涂膜防水施工工艺 编辑:程序博客网 时间:2024/06/05 06:36

this始终指向调用它的对象


通过几个例子弄清楚:<div id="test" onclick="mytest(this)">aaaa</div>

1、 alert(this); //object window,调用该段代码的是window

alert(this === window);//true,调用该段代码的是window


2、 var test = function(){
alert(this === window);
}
test();*/ //true,调用test对象的的依然是window


3、 var test = function(){
alert(this === window);
}
new test(); //false,使用了new创建了一个新的对象, 调用test的是这个新对象,不再是window


4、 var test = {
'a': 1,
'b': function(){
alert(this === test);
}
}
test.b(); //true,test对象调用


5、 var test = {
'a': 1,
'b': function(){
alert(this === test);
}
}
var test1 = test;
test1.b(); //true,虽然test1的值为test,但test1仍然是test对象,两个指的是同一个对象

var test = {
'a': 1,
'b': function(){
alert(this === test);
}
}
var test1 = test;
test.a = 2;
alert(test1.a);//2
,test1、test指的是同一个对象


6、 var test = {
'a': 1,
'b': {
'b1': function(){
alert(this === test);
}
}
};
test.b.b1();*///false,直接调用b1的是b而不是test


var test = {
'a': 1,
'b': {
'b1': function(){
alert(this === test.b);
}
}
};
test.b.b1(); //true


7、 var test = function(){
var innerTest = function(){
alert(this === test);
};
innerTest();
}
test(); //false,调用innerTest的是window对象,即使嵌套很多层,调用各个函数的都是window 对象


var test = function(){
var innerTest = function(){
alert(this === window);
var innerTest1 = function(){
alert(this === window);
};
innerTest1();
};
innerTest();
};
test(); //true, true


8、 var test = function(){
alert(this === window);
}
var test1 = {

}
test.apply(test1);//false,调用一对象的一个方法,以另一个对象替换当前对象,所以window对象已经被替换成test1


9、 var test = function(){
}
var my = function(){
this.a = function(){
alert(this === mytest2);
}
}
var mytest = new my();
test.prototype = mytest;
var mytest2 = new test();
mytest2.a(); //true,原型继承


10、var mytest = function(context){
alert(context.getAttribute('id'));
alert(this === window);
} //test, true,关于DOM对象的调用,依然是window

原创粉丝点击