JS高階---三種建立物件的方式
阿新 • • 發佈:2020-08-18
JS高階---三種建立物件的方式
- 字面量的方式 (例項物件)
- 呼叫系統的建構函式
- 自定義建構函式方式
//建立物件---->例項化一個物件,的同時對屬性進行初始化 var per=new Person("小紅",20);
自動逸建構函式建立物件做的事情:
1.開闢空間儲存物件 2.把this設定為當前的物件 3.設定屬性和方法的值 4.把this物件返回//例項物件 var per1 = { name: "小明", age: 20, sex: "男", eat: function () { console.log("吃臭豆腐"); }, readBook: function () { console.log("時間簡史") } } //呼叫系統的建構函式 var per2 = new Object(); per2.name = "小蘇"; per2.age = 30; per2.sex = "男"; per2.eat = function () { console.log("吃西瓜"); }; per2.play = function () { console.log("遊戲真好玩"); }; //自定義建構函式 function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; this.play = function () { console.log("天天打遊戲"); }; }; var per = new Person("小丁", 39, "女"); console.log(per instanceof Person);