如何在 JavaScript 中创建自己的 class 实现并将其传递给构造函数
How to create an own implementation of class in JavaScript and pass it a constructor
可能已经有这样的问题了,但是我没找到,还是有问题。我试过了:
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}`);
}
})
我觉得更像原生实现。但是我得到一个错误:'Person is not a constructor'。这两种方式有什么区别?很抱歉提出这样一个愚蠢的问题,我只是想弄清楚这个基本问题。感谢您的帮助。
方法 - 即:
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();
可能已经有这样的问题了,但是我没找到,还是有问题。我试过了:
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}`);
}
})
我觉得更像原生实现。但是我得到一个错误:'Person is not a constructor'。这两种方式有什么区别?很抱歉提出这样一个愚蠢的问题,我只是想弄清楚这个基本问题。感谢您的帮助。
方法 - 即:
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();