JS创建对象的几种方式(对象字面量/es6类/new操作符/工厂模式/原型模式等等)

本文详细介绍了JavaScript中使用构造函数、对象字面量、Object.create、类(包括类声明和类表达式)、工厂模式、ConstructorFunction以及原型模式创建对象的不同方法,并对比了它们的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* 三种基本的方式 */
//1.Object构造函数
let person = new Object();

//添加属性,方法
person.name = "Lucy";;
person.sayName = function(){
  console.log(this.name)
}

//2.对象字面量
let person = {
  name: "Lucy",
  sayName(){
    console.log(this.name)
  }
}

//3.Object.create
let person1 = Object.create(person)

//4.类(ES6) 有类声明和类表达式两种,类相比原型模式,具备原型模式的优点,代码封装更好
//类声明
class Person {
  constructor(name){
    this.name = name;
  }
  sayName(){
    console.log(this.name)
  }
}
const person2 = new Person("类声明")
person2.sayName()

//类表达式创建一个对象
let Person = class{
  constructor(name) {
    this.name = name;
  }
  sayName(){
    console.log(this.name)
  }
}
const person3 = new Person("类表达式")
person3.sayName()

//5.工厂模式
function createPersonFactory(name){
  let o = new Object();
  o.name = name;
  o.sayName = funciton(){
    console.log(this.name)
  };
  return 0;
}
let person4 = createPersonFactory("Lucy");
let person5 = createPersonFactory("Joe");

//6.ContructorFunction构造函数模式
function Person(name){
  this.name = name;
  this.sayName = function(){
    console.log(this.name)
  }
}
let person6 = new Person("Lucy");
let person7 = new Person("Joe");

person6.sayName(); // "Lucy"
person7.sayName(); // "Joe"

//new操作符
/**
  1. 在内存中创建一个新对象
  2. 这个新对象内部的 [[Prototype]] 特性被赋值为构造函数的 prototype 属性
  3. 构造函数内部的 this 被赋值为这个新对象(即 this 指向新对象)
  4. 执行构造函数内部的代码
  5. 如果构造函数返回非空对象(即一个对象引用),则返回该对象作为new表达式的结果,否则,返回刚创建的新对象。
 */
function newOperator(Constructor, ...args) {
  let thisValue = Object.create(Constructor.prototype);  // 对应上文操作步骤: 1、2
  let result = Constructor.apply(thisValue, args); // 对应上文操作步骤: 3、4
  return typeof result === 'object' && result !== null ? restult : thisValue; // 对应上文操作步骤: 5
}


//7.原型模式
function Person(){};
Person.prototype.name = "Lucy";
Person.prototype.sayName = function() {
  console.log(this.name);
}
let person8 = new Person();
person8.sayName(); // "Lucy"
let person0 = new Person();
person2.sayName(); // "Lucy"




// 8.组合模式
function Person(name){
  this.name = name;
}
Person.prototype = {
  constructor: Person,
  sayName: function() {
    console.log(this.name)
  }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值