<!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>