this 的指向

<script type="text/javascript">
        var color="红色";
        var myobj={
            color:"蓝色"
        }
        function showColor(){
            alert(this.color)  //this 指向调用它的那个对象
        }
      myobj.scolor=showColor;  //this指向myobj
      myobj.scolor();
      showColor()   //this指向Window(默认)

     //call改变this指向
    function test(){
        this.property="hello world"
    }
    test() //相当于window.test()
    alert(window.property)

    var obj1={}
    test.call(obj1); //改变this指向obj1
    alert(obj1.property)
</script>

猜你喜欢

转载自blog.csdn.net/qq_33325959/article/details/79620800