JavaScript创建对象的多种方式

155 阅读1分钟

JavaScript创建对象的几种方式(笔记):

1. 工厂模式

   function createPerson (name) {
       let obj = new Object();
       obj.name = name;
       obj.getName = function () {
          console.log(this.name);
       };
       return obj;
   };
   
   const person1 = createPerson('VT');
缺点:对象无法识别,因为所有实例都指向一个原型

2. 构造函数模式

   function Person (name) {
       this.name = name;
       this.getName = function () {
           console.log(this.name);
       };
   }
   
   const person1 = new Person('VT');
缺点:每次创建实例时,每个方法都要被创建一次
优点:实例可以识别为一个特定的类型

2.1 构造函数优化

   function Person (name) {
      this.name = name;
      this.getName = getName;
   }
   
   function getName () {
      console.log(this.name);
   }
   
   const person1 = new Person('VT');
优点:解决了每个方法都要被创建一次的问题

3. 原型模式

   function Person (name) {};
   Person.prototype.name = "VT";
   Person.prototype.getName = function () {
       console.log(this.name);
   }
   
   const person1 = new Person();
优点:方法不会重新创建
缺点:1.所有的属性和方法都被共享
     2.不能初始化参数

3.1 原型模式优化

   function Person (name) {};
   Person.prototype = {
      constructor: Person,
      name: 'VT',
      getName: function () {
         console.log(this.name);
      }
   }
   
   const person1 = new Person();
优点:实例通过contractor属性找到所属的构造函数
缺点:原型模式该有的缺点还是有的

4. 组合模式

   function Person (name) {
       this.name = name;
   };
   Person.prototype = {
       constructor: Person,
       getName: function () {
            console.log(this.name)
       }
   };
优点:该共享的共享,该私有的私有

5. 寄生构造函数模式

   function Person (name) {
       const o = new Object();
       o.name = name;
       o.getName = function () {
           console.log(this.name);
       };
       return o;
   };
   
  let person1 = new Person("Vt");
  
  console.log(person1 instanceof Person); // false
  console.log(person1 instanceof Object); // true

5.1 稳妥构造函数模式

   function person (name) {
       const o = new Object();
       o.sayName = function () {
           console.log(this.name);
       };
       return o;
   };
   
   
   var person1 = person('VT');

   person1.sayName(); // VT

   person1.name = "daisy";

   person1.sayName(); // VT

   console.log(person1.name); // daisy
所谓稳妥对象,指的是没有公共属性,而且其方法也不引用 this 的对象。

与寄生构造函数模式有两点不同:

1.  新创建的实例方法不引用 this
1.  不使用 new 操作符调用构造函数

稳妥对象最适合在一些安全的环境中。

稳妥构造函数模式也跟工厂模式一样,无法识别对象所属类型。