JS高階---工廠模式建立物件和自定義建構函式建立物件的區別
阿新 • • 發佈:2020-08-18
建立物件:工廠模式和自定義建構函式的區別
共同點: 都是函式, 都可以建立物件, 都可以傳入引數 區別: 工廠模式:- 函式名是小寫
- 有new,
- 有返回值
- new之後的物件是當前的物件
- 直接呼叫函式就可以建立物件
//工廠模式建立物件 function createObject(name, age) { var obj = new Object(); obj.name = name; onj.age = age; obj.sayHi = function () { console.log("您好"); };return obj; }
var per2 = createObject("小明", 20);
自定義建構函式:
- 函式名是大寫(首字母)
- 沒有new
- 沒有返回值
- this是當前的物件
- 通過new的方式來建立物件
//自定義建構函式建立物件 function Person(name, age) { this.name = name; this.age = age; this.sayHi = function () { console.log("您好"); }; }
varper1 = new Person("小紅", 20);