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
- Javascript中的this关键字
- JavaScript中的this关键字
- JavaScript 中的this 关键字
- Javascript中的关键字this
- JavaScript中的this关键字
- Javascript中的this关键字
- JavaScript中的this关键字
- JavaScript中的this关键字
- JavaScript中的this关键字
- Javascript中的this关键字
- JavaScript中的this关键字
- javaScript中的this关键字
- JavaScript中的this关键字
- JavaScript 中的 this 关键字
- javaScript中的this关键字
- JavaScript中的this关键字
- JavaScript 中的 this 关键字
- JavaScript中的this关键字
- spring既要(-)
- Android Studio项目精简结构,瘦体储存
- 物联网的长期演进技术
- 遗传算法小结(四)
- 整合spring cloud云服务架构
- JavaScript中的this关键字
- httpClient 使用说明
- SSM入门项目-2-类目、图片、富文本
- vue+elementUi时间控件
- 眼下最流行的五大CSS框架,你都知道么?(转)
- css 水平旋转
- Python变量的原理
- 关于ssh框架的搭建问题,记录详细流程
- Spring对JDBC的支持JdbcTemplate模板类