javascript遍歷對象屬性和方法

 

使用javascript遍歷對象的屬性和方法javascript

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="lib/jquery-1.8.2.js"></script>
    <script type="text/javascript">

        //對象
        function Programmer() {
            this.name = "李小牛";
            this.sex = "";
            this.age = 25;
            this.work = proFun;
        }

        //方法
        function proFun() {
            $("#function").append("程序員的工做是寫代碼");
        }

        function foreachObj() {
            //聲明對象
            var pro = new Programmer();
            //遍歷對象屬性
            for (var p in pro) {
                //判斷是否爲方法
                if (typeof (pro[p]) == "function") {
                    //執行放阿飛
                    pro[p]();
                } else {
                    //打印屬性
                    $("#attribute").append(p + ":" + pro[p] + "\t");
                }
            }
        }
    </script>
</head>
<body>
    <input type="button" value="執行對象方法" onclick="foreachObj()" />
    <div id="attribute"></div>
    <div id="function"></div>
</body>
</html>
相關文章
相關標籤/搜索