JavaScript this用法

修抗發表於2018-05-02
  • 當this為全域性變數時,this為window物件
<script>
    // 在全域性變數中,this為window
    window.onload= function(){
        alert(window);//object window
    }
    this.onload= function(){
        alert(this);//object window
    }
</script>
  • 當this在函式中時,this為window物件
<script>
    function xiu(kang){
        this.sear = kang;
    }
    xiu("修抗");
    alert(sear);
</script>
  • 當this在物件中,this就為該物件(person)

 

<script>
    var name = "修抗";
    var person = {
        name: "user",
        xiu: function(){
            alert(this.name);
        }
    }
    person.xiu();//user
</script>

 

  • 當this遇上new時,this為新建立的物件(kang)
<script>
    function Fun(){
        this.name = "修抗";
    }
    var kang = new Fun();
    alert(kang.name); //修抗
</script>
  • 當this在內部函式中,this為window
<script>
    var name = "修抗";
    var person = {
        name : "user",
        hello : function(){
            var sayhello = function() {
                alert(this.name);
            };
            sayhello();
        }
    }
person.hello();//修抗
</script>
  • 當this在內部函式中,如果在物件中將this作為變數儲存下來,this就指向該物件
<script>
    var name = "修抗";
    var person = {
        name : "user",
        hello : function(){
            var th = this;
            var sayhello = function() {
                alert(th.name);
            };
            sayhello();
        }
    }
person.hello();//user
</script>

··END··

相關文章