1. 程式人生 > >JavaScript-04-JS產生物件以及批量產生物件

JavaScript-04-JS產生物件以及批量產生物件

1.1建立物件

    <script text="text/javascript">
        //1.建立物件
        //this this 所在的函式屬於哪個物件,this就代表這個物件
        //1.1直接建立
        var dog = {
            name: 'San',
            age: 18,
            height: 
1.55, dogFriends: ['Bob','Lili'], eat:function (someThing) { console.log( this.name +'' + someThing); }, run:function (someWhere) { console.log(this.name +'' + someWhere); } };//object console.log(
typeof dog); //1.2輸出這隻狗物件的屬性和行為 console.log(dog.age,dog.dogFriends); dog.eat(''); dog.run('健身房'); </script>

2.通過建構函式批量產生物件

    <script type="text/javascript">
        //通過建構函式批量產生物件
        //普通函式->建構函式
        var Dog = function () {
            console.log(
'這是一個普通函式'); }; //普通呼叫 Dog(); // alloc init -> new var dog1 = new Dog(); var dog2 = new Dog(); console.log(dog1,dog2); </script>

3.驗證批量產生物件

     <script type="text/javascript">
        //建立建構函式 -> 抽象
        var Dog = function () {
            this.name = null;
            this.age = null;
            this.dogFriends = [];
            this.height = null;
            this.eat = function (someThing) {
                console.log(this.name + '' + someThing);
            }
            this.run = function (someWhere) {
                console.log(this.name + '' + someWhere);
            }
        }
        //批量產生物件
        var dog1 = new Dog();
        dog1.name = 'Peter';
        dog1.age = 15;
        dog1.dogFriends = ['A','B'];
        var dog2 = new Dog();
        dog2.name = 'Bob';
        dog2.age = 18;
        dog2.dogFriends = ['C','D'];
        console.log(dog1,dog2);

        //建立建構函式 -> 抽象
        var Dog1 = function (name,age,dogFriends,height) {
            this.name = name;
            this.age = age;
            this.dogFriends = dogFriends;
            this.height = height;
            this.eat = function (someThing) {
                console.log(this.name + '' + someThing);
            }
            this.run = function (someWhere) {
                console.log(this.name + '' + someWhere);
            }
        }
        var dog3 = new Dog1('Peter',15,['A','B'],1);
        console.log(dog3);
    </script>