1. 程式人生 > 實用技巧 >JS高階---工廠模式建立物件和自定義建構函式建立物件的區別

JS高階---工廠模式建立物件和自定義建構函式建立物件的區別

建立物件:工廠模式和自定義建構函式的區別

共同點: 都是函式, 都可以建立物件, 都可以傳入引數 區別: 工廠模式:
  1. 函式名是小寫
  2. 有new,
  3. 有返回值
  4. new之後的物件是當前的物件
  5. 直接呼叫函式就可以建立物件
    //工廠模式建立物件
    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);

自定義建構函式:
  1. 函式名是大寫(首字母)
  2. 沒有new
  3. 沒有返回值
  4. this是當前的物件
  5. 通過new的方式來建立物件
    //自定義建構函式建立物件
    function Person(name, age) {
      this.name = name;
      this.age = age;
      this.sayHi = function () {
        console.log("您好");
      };
    }
    var
per1 = new Person("小紅", 20);