this关键字的用法
2016-05-09 20:22
246 查看
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>javascript中this关键字的理解</title>
</head>
<body>
<div id="div">
javascript中的this关键字理解
</div>
<script type="text/javascript">
// 1 纯粹的函数调用
var a = {};
a.x = 10;
a.y = function(){
alert(this.x);
}
a.y();
var x = 100;
function test(){
alert(this.x);
}
test();
// 2 作为对象的方法调用
var test = function(){
alert(this.x);
}
var x = "this is a window property";
var obj = {};
obj.x = 10;
obj.y = function(){
alert(this.x);
}
var obj2 = obj.y;
obj.y();
test();
obj2();
//3 call apply
//call
function changeStyle(type, value){
this.style[type] = value;
}
var oDiv = document.getElementById('div');
changeStyle.call(oDiv, 'fontSize', '40px');
//apply
function changeStyle(type, value){
this.style[type] = value;
}
var oDiv = document.getElementById('div');
changeStyle.apply(oDiv, ['fontSize', '40px']);
//4. 作为构造函数调用
function test(){
this.x = 1;
}
var o = new test();
alert(o.x);
</script>
</body>
</html>
<html>
<head>
<meta charset="utf-8"/>
<title>javascript中this关键字的理解</title>
</head>
<body>
<div id="div">
javascript中的this关键字理解
</div>
<script type="text/javascript">
// 1 纯粹的函数调用
var a = {};
a.x = 10;
a.y = function(){
alert(this.x);
}
a.y();
var x = 100;
function test(){
alert(this.x);
}
test();
// 2 作为对象的方法调用
var test = function(){
alert(this.x);
}
var x = "this is a window property";
var obj = {};
obj.x = 10;
obj.y = function(){
alert(this.x);
}
var obj2 = obj.y;
obj.y();
test();
obj2();
//3 call apply
//call
function changeStyle(type, value){
this.style[type] = value;
}
var oDiv = document.getElementById('div');
changeStyle.call(oDiv, 'fontSize', '40px');
//apply
function changeStyle(type, value){
this.style[type] = value;
}
var oDiv = document.getElementById('div');
changeStyle.apply(oDiv, ['fontSize', '40px']);
//4. 作为构造函数调用
function test(){
this.x = 1;
}
var o = new test();
alert(o.x);
</script>
</body>
</html>
相关文章推荐
- java推荐书籍及下载
- 第十一周【项目1 - 点-圆-圆柱类族的设计3】
- 线程
- C++ VS 操作mysql配置
- Storm和Spark的选择
- 不可不知的robots.txt文件
- robots.txt使用和优化技巧
- 一些很少用到但是用到时又很抓鸡的代码
- 第十周第十一周项目1阅读程序(9)
- Linux下的文件系统和磁盘管理(初学者希望各位技术大神指导)
- AlertView&ActionSheet
- 深入浅出Shell编程 Shell变量介绍
- 【HDU】 3572 Task Schedule
- matlab中有哪些有趣的命令?好玩的matlab彩蛋
- linux目录结构
- ajax 跨域请求以及跨域cookie提交
- linux 字符处理指令 awk
- 编程之美之找出故障机器
- Android使用multidex解决方法数越界问题65536
- cisco HSRP负载均衡