javascript - 如何在 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}`);
}
})
我认为它更类似于原生实现。但我收到一个错误:“人不是构造函数”。这两种方式有什么区别?对不起,这么愚蠢的问题,我只是想弄清楚这个基本的东西。谢谢你的帮助。
解决方案
方法——即:
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();
推荐阅读
- angular - Ionic 应用程序和 Angular 应用程序之间的共享组件
- json - cy.request 正文中的 JSON
- php - 通过引用取消设置会话不起作用
- python - 虽然循环不能很好地适应时间
- amazon-web-services - ecs.amazonaws.com 和 ecs-tasks.amazonaws.com 有什么区别?
- sapui5 - 如何在没有数据绑定的情况下使用 sapui5 SmartField?
- javascript - 两个javascript参数如何传递“this”
- arrays - mongodb 匹配数组中的项目作为聚合管道的一部分
- javascript - Weglot 链接挂钩不起作用(在粘性标题上)
- vue.js - Vue 数据、计算和方法