zoukankan      html  css  js  c++  java
  • JavaScript this用法

    • 当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··

  • 相关阅读:
    什么是 DLL?
    如何用vc创建和读取xml文件??
    VC中调用 Excel 的总结
    Excel.cpp和Excel.h
    SQL中也可以用格式字符串定制日期转字符串
    REVERT权限切换
    透明数据加密
    批量恢复数据库
    FILESTREAM
    eclipse Tomcat热启动maven install Jrebel
  • 原文地址:https://www.cnblogs.com/xiukang/p/8980241.html
Copyright © 2011-2022 走看看