javascript面向對象(給對象添加屬性和方法的方式)

在定義對象時,直接把屬性和方法添加,

<script type="text/javascript">

        //給對象直接在定義時添加屬性和方法
        var g = {
                    name:"張三",
                    age:23,
                    sum:function(i,j)
                    {
                        return i+j;
                    }
                };

            alert(g.name);
            alert(g.age);
            alert(g.sum(20,25));

    </script>

2 通過原型prototype模式給對象添加屬性和方法,

<script type="text/javascript">
        //應用原型,添加成員變量
        //創建一個構造函數或者類
        var People = function(){};
        //創建對象,通過構造函數
        var p1 = new People();
        var p2 = new People();
        //通過原型prototype 給People類的所有對象添加成員變量
        var pt = People.prototype;
        pt.name = "明銘";
        pt.age = 23;
        //通過原型prototype,給People添加方法
        pt.add = function(i,j)
                         {
                            return i+j;
                         }
        alert(p1.name);
        alert(p2.age);
        alert(p1.age == p2.age);
        alert(p2.add(20,20));
        //People不是靜態成員,因此不能直接調用屬性(輸出undefind)
        alert(People.age);
    </script>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章