JavaScript中创建对象有哪些方法?如何理解this的指向问题?

更新于
2026-09-25 01:22:08
0阅读来源:SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1637个文字,预计阅读时间需要7分钟。

JavaScript中创建对象有哪些方法?如何理解this的指向问题?

目录+工厂模式+构造函数模式+关于this+原型模式+工厂模式+工厂模式一般用于抽象创建特定对象的过程,是按照特定接口创建对象的方式。+function createPerson(name, age) {+ let o={};+ o.name=name;+}+

目录
  • 工厂模式
  • 构造函数模式
    • 关于this
  • 原型模式

    工厂模式

    工厂模式一般用于抽象创建特定对象的过程,是按照特定接口创建对象的方式。

    function createPerson(name, age) { let o = {}; o.name = name; 0.age = age; o.study = function() { console.log(`${this.name} is studying`) } return o } const p1 = createPerson('张三', 18) const p2 = createPerson('李四', 20) p1.study() // 张三 is studying

    值得一提的是,如果在createPerson函数中,o.study改为箭头函数,那么打印的 this 会发生改变,这是因为箭头函数发生了this指向的问题。

    阅读全文

    本文共计1637个文字,预计阅读时间需要7分钟。

    JavaScript中创建对象有哪些方法?如何理解this的指向问题?

    目录+工厂模式+构造函数模式+关于this+原型模式+工厂模式+工厂模式一般用于抽象创建特定对象的过程,是按照特定接口创建对象的方式。+function createPerson(name, age) {+ let o={};+ o.name=name;+}+

    目录
    • 工厂模式
    • 构造函数模式
      • 关于this
    • 原型模式

      工厂模式

      工厂模式一般用于抽象创建特定对象的过程,是按照特定接口创建对象的方式。

      function createPerson(name, age) { let o = {}; o.name = name; 0.age = age; o.study = function() { console.log(`${this.name} is studying`) } return o } const p1 = createPerson('张三', 18) const p2 = createPerson('李四', 20) p1.study() // 张三 is studying

      值得一提的是,如果在createPerson函数中,o.study改为箭头函数,那么打印的 this 会发生改变,这是因为箭头函数发生了this指向的问题。

      阅读全文