您的位置:首页 > 其它

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: