1. 程式人生 > >JS學習筆記(物件基礎操作)

JS學習筆記(物件基礎操作)

建構函式寫法一:

 function Dog(name, age, dogFriends) {
        // 1.1 屬性
        this.name = name;
        this.age = age;
        this.dogFriends = dogFriends;

        // 1.2 方法
        this.eat = function (someThing) {
            console.log(this.name + "在吃" + someThing);
        };

        this.run = function (someWhere) {
            console.log(this.name + "跑" + someWhere);
        }
    }

建立物件:var smallDog = new Dog("小花", 1);       smallDog.age = 10;

建構函式寫法二:

unction Dog(option) {
        // 1.1 屬性
        this.name = option.name;
        this.age = option.age;
        this.dogFriends = option.dogFriends;

        // 1.2 方法
        this.eat = function (someThing) {
            console.log(this.name + "在吃" + someThing);
        };

        this.run = function (someWhere) {
            console.log(this.name + "跑" + someWhere);
        }
    }

建立物件:var smallDog = new Dog({name:"小花", age:1});      smallDog.age = 10;
這種就是將所有的屬性存在了一個數組裡面

倘若我們要臨時新增一個建構函式裡面沒有的屬性或者方法,則可以直接新增:

Dog.say = function(){

};

Dog.leg=10;