js對象使用

以下是js對象使用的兩種方式

<script type="text/javascript">
        var people = function () {
         
        }
        
        //方法1
        people.prototype =
        {
         age: 18,
         name:'jack',
         sayHello:function(){
                alert("你好");
            }
        }

        //方法2
        function MyObject() {
           var name = "myObject";
            this.type = "class";
            this.methodA = function () {
                alert(this.name);
            }
            this.methodB = function () {
                return this.type;
            }
        }



        window.onload = function () {
            var p = new people();
            p.age = 20;
            alert(p.age);

            var myObject = new MyObject();
            myObject.name = 'hahhahah'
            alert(myObject.name);
            myObject.methodA();
            var type = myObject.methodB();
            alert(type);
        }
    </script>

 

  

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