js Class 与 普通构造函数有何区别

博客介绍了JS构造函数、class基本语法和继承。继承包括构造函数形式和Class继承。总结指出,class在语法上更贴近面向对象写法,实现继承也更易读易理解。

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

 

一、js构造函数

    let myCanvas = this.$refs.myCanvas
    var ctx = myCanvas.getContext('2d')

    function Circle (x, y, r, color) {
        this.x = x
        this.y = y
        this.r = r
        this.color = color
      }

      Circle.prototype.render = function () {
        ctx.beginPath()
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true)
        ctx.fillStyle = this.color
        ctx.fill()
      }

      Circle.prototype.update = function () {
        this.x += 1
      }

      var yuan = new Circle(100, 100, 1, 'red')
      var timer
      clearInterval(timer)
      timer = setInterval(() => {
        // ctx.clearRect(0, 0, 800, 600)
        yuan.update()
        yuan.render()
        if (yuan.x === 800) {
          clearInterval(timer)
        }
      }, 15)

 

二、class基本语法

    let myCanvas = this.$refs.myCanvas
    var ctx = myCanvas.getContext('2d')
    class Circle {
        constructor (x, y, r, color) {
          this.x = x
          this.y = y
          this.r = r
          this.color = color
        }
        render () {
          ctx.beginPath()
          ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true)
          ctx.fillStyle = this.color
          ctx.fill()
        }
        update () {
          this.x += 1
        }
      }
      const yuan = new Circle(100, 100, 1, 'red')
      var timer
      clearInterval(timer)
      timer = setInterval(() => {
        // ctx.clearRect(0, 0, 800, 600)
        yuan.update()
        yuan.render()
        if (yuan.x === 800) {
          clearInterval(timer)
        }
      }, 15)

三、继承

1、构造函数形式的继承

 

//动物
function Animal(){
    this.eat = function (){
        console.log('Animal eat')
    }
}

//狗
function Dog() {
    this.bark = function (){
        console.log('Dog bark')
    }
}

Dog.prototype = new Animal()

var hashiqi = new Dog()
hashiqi.bark()
hashiqi.eat()

 

2、Class继承

class Animal {
    constructor(name){
        this.name = name
    }
    eat(){
        alert(this.name + ' eat')
    }
}

class Dog extends Animal {
    constructor(name){
        super(name) //super就是被继承的对象的constructer
    }
    say(){
        alert(this.name + ' say')
    }
}

const dog = new Dog('哈士奇')
dog.say()
dog.eat()

 四、总结


1、class在语法上更贴近面向对象的写法。
2、class实现继承更加易读易理解。

 

<think>我们正在讨论JavaScript中工厂模式构造函数创建对象的本质区别。根据引用内容,我们可以总结如下: 1. **工厂模式**: - 通过一个工厂函数封装对象的创建过程,函数内部显式创建对象(如`new Object()`),设置属性方法,最后返回该对象。 - 每次调用工厂函数都会创建一个新对象,但无法解决对象类型识别问题(即创建的所有对象都是`Object`类型,无法识别为特定类型)。 2. **构造函数模式**: - 使用自定义构造函数(函数名通常首字母大写),通过`new`操作符调用。 - 构造函数内部使用`this`来添加属性方法,没有显式创建对象返回对象(由`new`操作符自动完成)。 - 创建的对象实例可以标识为特定类型(即实例的`constructor`属性指向构造函数,且可以通过`instanceof`检测类型)。 ### 本质区别总结: | **区别点** | **工厂模式** | **构造函数模式** | |--------------------|---------------------------------------------|-------------------------------------------| | **对象创建方式** | 显式创建对象(如`new Object()`)并返回 | 由`new`操作符隐式创建对象,无需显式返回 | | **对象类型识别** | 所有对象都是`Object`类型,无法识别具体类型 | 对象实例标识为构造函数类型(如`Person`) | | **内部属性指向** | 无特殊内部属性指向工厂函数 | 实例的`constructor`属性指向构造函数 | | **`this`的指向** | 在工厂函数内部,`this`指向不固定(可能全局)| 构造函数内`this`指向新创建的实例 | | **内存占用** | 方法在每次创建时都生成新函数(占用更多内存)| 同样存在方法重复创建问题(可结合原型解决)| ### 代码示例对比: #### 工厂模式: ```javascript function createPerson(name, age) { var o = new Object(); // 显式创建对象 o.name = name; o.age = age; o.sayName = function() { console.log(this.name); }; return o; // 显式返回对象 } const p1 = createPerson("Alice", 25); console.log(p1 instanceof Object); // true console.log(p1.constructor); // [Function: Object] (无法识别为Person) ``` #### 构造函数模式: ```javascript function Person(name, age) { // 隐式创建对象: this = new Object() this.name = name; this.age = age; this.sayName = function() { console.log(this.name); }; // 隐式返回: return this; } const p2 = new Person("Bob", 30); console.log(p2 instanceof Person); // true (可识别类型) console.log(p2.constructor); // [Function: Person] ``` ### 关键区别解析: 1. **类型识别**:构造函数模式创建的对象具有明确的类型标识(通过`instanceof``constructor`属性),而工厂模式创建的对象均为`Object`类型[^3][^4]。 2. **创建机制**:构造函数依赖`new`操作符自动完成对象创建返回,工厂模式需手动创建返回对象。 3. **设计意图**: - 工厂模式是抽象创建过程的设计模式,适用于需要灵活控制对象创建的场合。 - 构造函数模式是JavaScript模拟面向对象类的机制,强调类型标识实例关系。 > 最佳实践:若需要类型识别继承特性,优先使用构造函数模式(或ES6 Class);若仅需简单封装创建过程,工厂模式更轻量[^3][^4]。 §§相关问题§§ 1. 如用工厂模式实现跨浏览器的自定义弹窗组件? 2. 构造函数模式中如优化方法重复创建的问题? 3. JavaScript的`new`操作符底层具体执行了哪些步骤? 4. ES6 Class语法构造函数模式有关联? 5. 在什么场景下工厂模式比构造函数模式更适用?</think>### JavaScript 工厂模式构造函数创建对象的本质区别 #### 1. **核心目的差异** - **工厂模式**:抽象对象创建过程,**关注对象创建本身** 通过函数封装创建逻辑,隐藏实例化细节,返回新对象(通常是普通 Object)[^2][^5] ```javascript function createPerson(name) { const obj = new Object(); // 显式创建对象 obj.name = name; obj.sayName = function() { console.log(this.name) }; return obj; // 显式返回对象 } ``` - **构造函数模式**:**定义对象类型标识** 通过 `new` 操作符创建特定类型的实例,隐含创建返回对象[^3][^4] ```javascript function Person(name) { // 隐含创建:this = new Object() this.name = name; this.sayName = function() { console.log(this.name) }; // 隐含返回:return this } ``` #### 2. **对象类型识别(关键区别)** | **模式** | `instanceof` 检测 | `constructor` 属性 | 类型标识能力 | |----------------|--------------------------|--------------------------|--------------| | 工厂模式 | `obj instanceof Object` ✅ | 指向 `Object` | ❌ 无类型标识 | | 构造函数模式 | `obj instanceof Person` ✅ | 指向构造函数 `Person` | ✅ 强类型标识 | **示例验证**: ```javascript // 工厂模式 const factoryObj = createPerson("Alice"); console.log(factoryObj instanceof Object); // true console.log(factoryObj instanceof createPerson); // false ❌ 无法识别工厂函数 // 构造函数模式 const constructorObj = new Person("Bob"); console.log(constructorObj instanceof Person); // true ✅ 识别为Person类型 console.log(constructorObj.constructor === Person); // true ``` #### 3. **创建机制差异** | **特性** | 工厂模式 | 构造函数模式 | |------------------|---------------------------|---------------------------| | 对象创建 | 显式 `new Object()` | 隐式通过 `new` 操作符创建 | | 返回值 | 必须显式 `return` 对象 | 自动返回 `this` | | `this` 指向 | 指向新创建的对象 | 指向新实例 | | 命名规范 | 驼峰命名(如 createXxx) | 首字母大写(如 Person) | #### 4. **内存占用问题** - **共同缺陷**:两种模式都会**为每个对象创建独立的方法副本** ```javascript const p1 = new Person("Tom"); const p2 = new Person("Jerry"); console.log(p1.sayName === p2.sayName); // false ❌ 方法重复创建 ``` - **解决方案**:结合原型模式共享方法 ```javascript function Person(name) { this.name = name; } // 方法定义在原型上 Person.prototype.sayName = function() { console.log(this.name) }; ``` #### 5. **适用场景对比** - **工厂模式适用**: - 需要创建多种异构对象 - 不关心对象具体类型 - 跨环境对象创建(如浏览器兼容性处理) - **构造函数模式适用**: - 需要明确对象类型标识 - 实现基于原型的继承链 - `instanceof` 类型检测配合使用 > **本质总结**:工厂模式是**创建过程抽象**,构造函数模式是**类型定义机制**。前者解决"如创建",后者解决"创建什么"并建立类型标识[^3][^4]。 --- ### 相关问题 1. 如用工厂模式实现跨浏览器的自定义弹窗组件? 2. 构造函数模式中如优化方法重复创建的问题? 3. JavaScript 的 `new` 操作符底层具体执行了哪些步骤? 4. ES6 Class 语法构造函数模式有关联? 5. 在什么场景下工厂模式比构造函数模式更适用?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值