首页 > 解决方案 > 如何在 JavaScript 中创建自己的类实现并将其传递给构造函数

问题描述

也许这样的问题已经存在,但我没有找到它,我仍然有问题。我试过了:

function defClass(obj) {
    const constructor = obj.constructor;
    constructor.prototype = obj;
    return constructor;
}

接着:

const Person = defClass({
    constructor: function (name) {
        this.name = name;
    },
    voice() {
        console.log(`Hello, I'm ${this.name}`);
    } 
})

有用。但是如果我想使用这样的构造函数怎么办:

const Person = defClass({
    constructor(name) {
        this.name = name;
    },
    voice() {
        console.log(`Hello, I'm ${this.name}`);
    } 
})

我认为它更类似于原生实现。但我收到一个错误:“人不是构造函数”。这两种方式有什么区别?对不起,这么愚蠢的问题,我只是想弄清楚这个基本的东西。谢谢你的帮助。

标签: javascriptobjectmethodsthisprototype

解决方案


方法——即:

someMethodName() {
}

不能作为构造函数调用 - 你会得到你看到的错误。将方法改为函数:

function defClass(obj) {
  const constructor = obj.constructor;
  constructor.prototype = obj;
  return constructor;
}

const Person = defClass({
  constructor: function(name) {
    this.name = name;
  },
  voice() {
    console.log(`Hello, I'm ${this.name}`);
  }
})

const p = new Person('foo');
p.voice();

或者调用时不要使用new

function defClass(obj) {
  const constructor = obj.constructor;
  constructor.prototype = obj;
  
  return function(...args) {
    const instance = Object.create(obj);
    constructor.apply(instance, args);
    return instance;
  };
}

const Person = defClass({
  constructor(name) {
    this.name = name;
    return this;
  },
  voice() {
    console.log(`Hello, I'm ${this.name}`);
  }
})

const p = Person('foo');
p.voice();


推荐阅读