js 作用域问题

来源:互联网 发布:公司统计所用软件 编辑:程序博客网 时间:2024/06/04 19:58

1.js中的作用域问题

window.onload = function(){var box = document.getElementById('aa');box.onclick = function(){alert(this);     //返回[object HTMLDivElement],此时的this代表着box(因为是被box的事件绑定的)toBlue();        //当执行这一行时,this就代表着window了toBlue.call(this);  //所以在此处应该用call来使用box对象执行toBlue函数,                                    //PS:这里面的this是指当前的匿名函数(就是被box.onclick绑定的),                                    //   匿名函数的当前对象是box,这点可以从上面alert(this)中看出}}function toBlue(){this.className = 'pox';this.onclick = toRed;}function toRed(){this.className = 'box';this.onclick = toBlue;}
顺便写上html代码(乱写的):

<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>北京精时恒达</title><link rel="stylesheet" href="./style.css">        <style>            .box{    width:200px;    height:200px;    background:red;    overflow:scroll;    padding:10px;    border:10px solid black;    margin:10px;}.pox{    width:200px;    height:200px;    background:blue;    overflow:scroll;    padding:10px;    border:10px solid black;    margin:10px;}        </style></head><body><div class="box" id="aa">123aaaaaasdasdsadsadsadsadsadassssssssssssssssdasdasdasdasdasdddddddddddddd<div id="ee">444<div id="tt">555</div></div></div><script src="js/common.js"></script></body></html>


0 0
原创粉丝点击