javascript中的this(2)

来源:未知 责任编辑:责任编辑 发表时间:2013-12-18 11:34 点击:

                        this . _traceXhr ( xhr ); // error here! 'this' is xhr now
                    }
                },
                _traceXhr : function ( _xhr ){
                    console . log ( _xhr );
                }
            }
        </ script >
        这里的错误比较明显了吧,function() {this._traceXhr(xhr);}是个函数,这时候是绑定到xhr上运行的,那里面的this自然就指向xhr而不再是o2。
正确的写法是o2._traceXhr(this);    (ps,实际的应用中可能是这样的,一般会定义一个“类”,噢o2只是这个类的实例,那么定义类的时候需要这样写:
        < script type = "text/javascript" >
function ClazzO (){
}

ClazzO . prototype . xhr = null ;
ClazzO . prototype . execute = function (){
var _self = this ;
xhr . onreadystatuschange = function (){
_self . _traceXhr ( this );
}
}
ClazzO . prototype . _traceXhr = function ( _xhr ){
console . log ( _xhr );
}
</ script >
        execute里用一个临时变量保存一下善变的this,防止到了onxxxchange里面的时候找不到他了。
主要是这一类问题导致this的变化,另外还有一些是和dom对象联系在一起的

2. dom对象event里的this
a: <input type = "button" id = "a" onclick = " javascript : console . log ( this . value ) " value = "click me a" />
这种写法输出结果和我们想的一样:click this。但有些同学就提意见了,在html里面夹杂太多的js代码不好,而且有时由于函数太复杂含有' or "导致根本不能写在这里面,最好抽出来放到一个函数里:
b: <input type = "button" id = "b" onclick = " javascript : clicked () " value = "click me b" />
<script type = "text/javascript" >
function clicked () {
console . log ( this . value );
}
</script>
来看浏览器帮我们做了什么: onclick="[js code]"
浏览器会帮我们生成(这点我不确定,但按这种方式理解可以行得通)
[dom].onclick = function() {[js code]}
好,看看上面两个都发生了什么:
        <script type = "text/javascript" >
// a
document . getElementById ( "a" ). onclick = function () {

发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • Gb2312转utf-8编码的方法(vbs+js)
  • 如何使用Ajax技术开发Web应用程序(1)
  • js跳转路径问题
  • JavaScript模仿桌面窗口
  • 用js检测两个线段是否相交
  • 运用JavaScript构建你的第一个Metro式应用程序(on Windows
  • 我知道的JavaScript -- 设计模式(桥接)应用之 – 验证器
  • 我是如何去了解jquery的(六),案例之幻灯片轮换
  • Jquery封装幻灯片效果
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1