[code=HTM]
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
var $this = this;

var v1 = "";
var v2 = "";

function a() {
v1 = this;

alert("2:" + ($this == this));
this.userName = "zhangsan";
alert("3:" + userName);
}

function b() {
v2 = this;

alert("4:" + ($this == this));
var tempB = a;
tempB();
this.userName = "android";
alert("5:" + userName);
tempB();

}
b();
alert(v1 == v2); //方法a和方法b中的this不是同一个对象,为什么对象相等?</script></body>
</html><!-- 
问题:
1:
        var $this = this;中的this和方法a,b中的this,不是同一个对象;可是为什么相等
要是同一个对象在调用下面代码之后
var tempB = a;
tempB();
this.userName = "android";
alert("5:" + userName);
tempB(); //this的指向在上面不是改变了么,为什么此时弹出的结果还是zhangsan,而不是android呢?
        2:在方法最外面的this和在a,b方法中的this的区别?
------------------------------------
自己也是刚去接触JavaScript,请高手指点 -->[/code]

解决方案 »

  1.   

    看看这篇文章是否有帮助
    http://wenku.baidu.com/view/46c665ed102de2bd960588f1.html
      

  2.   


    严格相等(同一对象),应用alert(v1 === v2); 判断
      

  3.   

    var $this = this;function a() {
    v1 = this;
    alert("a-this:" + ($this === this));
    ……
    function b() {
    v2 = this;
    alert("b-this:" + ($this === this));你这些调用,this都是window。自然同一对象。1+1在算对的情况下就等于2。
      

  4.   


    <script type="text/javascript"> 
    var $this = this; 
    var v1 = ""; 
    var v2 = ""; 

    function a() { 
    v1 = this;
    };
    function b() { 
    v2 = this;
    };
    var fn1 = {};
    fn1.m1 = a;

    var fn2 = {};
    fn2.m2 = b;

    fn1.m1();
    fn2.m2();

    alert("$this=" + $this + " ,v1=" + v1 + " ,v2=" + v2);</script>说白了是this的运行环境上下文不同造成的!!!