0
点赞
收藏
分享

微信扫一扫

一文看懂图像格式 RAW、RGB、YUV、Packed/Unpacked、Bayer、MIPI、Planar、Semi-Planar、Interleaved

在JavaScript中,有多种方式可以创建对象。以下是常见的六种创建对象的方式:

1:字面量 (Literal) 方式:

使用对象字面量语法直接创建对象。

const obj = { 
  key1: value1,
  key2: value2
};
2:构造函数 (Constructor) 方式:

使用构造函数创建对象,可以通过 new 关键字实例化一个对象。


function Person(name, age) {
  this.name = name;
  this.age = age;
}

const person = new Person('John', 25);
3:Object.create() 方式:

使用 Object.create() 方法创建一个新对象,可以指定原型对象和属性描述符。


const protoObj = {
  greet() {
    console.log('Hello!');
  }
};

const obj = Object.create(protoObj);
obj.name = 'John';
4:工厂模式 (Factory) 方式:

使用工厂函数创建对象,函数内部返回一个新的对象。

function createPerson(name, age) {
  return {
    name: name,
    age: age
  };
}

const person = createPerson('John', 25);
5:ES6 类 (Class) 方式:

使用类和构造函数创建对象,通过 new 关键字实例化一个对象。

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

const person = new Person('John', 25);
6:单例模式 (Singleton) 方式:

创建一个只有一个实例的对象。

    const singleton = (function() {
      let instance;

      function createInstance() {
        const object = new Object('Singleton Instance');
        return object;
      }

      return {
        getInstance() {
          if (!instance) {
            instance = createInstance();
          }
          return instance;
        }
      };
    })();

    const instance1 = singleton.getInstance();
    const instance2 = singleton.getInstance();
    console.log(instance1 === instance2); // true

这些是常见的创建对象的方式,每种方式都有其适用的场景和特点。

举报

相关推荐

0 条评论