gpt4 book ai didi

javascript - 继承Javascript类方法

转载 作者:行者123 更新时间:2023-11-28 17:53:19 25 4
gpt4 key购买 nike

假设我有两个 API,我想从第一个 API 继承类,但使用 .prototype.toJSON() 修改响应。

当我继承第一个类时,如何才能继承类方法。

一个例子

//file v1/models/users.js
var UserModel = function() {
this.id = 0;
this.firstName = '';
this.lastName = '';
}

UserModel.find = function(q, callback) {
//find any user that matches q and map them to UserModel
if (err) return callback(err, null);
callback(null, users);
}

module.exports = UserModel;

以及下一个版本

//file v2/models/users.js
var UserModel = require('../v1/models/users');

function UserModelV2() {
UserModel.call(this);
}

UserModelV2 = Object.create(UserModel.prototype);
UserModelV2.prototype.constructor = UserModel;

UserModelV2.prototype.toJSON = function() {
var obj = {};
obj.firstName = 'foo';
return obj;
}
module.exports = UserModelV2;

当我现在尝试打电话时

var User = require('./v2/models/users');
User.find(1);

我收到一条错误消息,提示 User.find 不存在。

我知道我只是继承了原型(prototype)属性,但我在任何地方都找不到继承类方法的示例。

最佳答案

不要将 find 直接添加到 UserModel 上,因为这会导致该方法仅添加到一个实例。

将其添加到原型(prototype)中:

UserModel.prototype.find = function(id) {
//find the user by id and return
}

因为 UserModel 的所有实例都将从构造函数的原型(prototype)继承。

然后,您的下一个版本将从第一个版本继承,如下所示:

// Constructor of sub-class
function UserModelV2() {
// Call the prototype.constructor, not just .constructor
UserModel.prototype.constructor.call(this);
}

// Perform inheritance
UserModelV2.prototype = new UserModel();

// Correct the constructor of the prototype
UserModelV2.prototype.constructor = UserModelV2;

// Extend the sub-class
UserModelV2.prototype.toJSON = function() {
var obj = {};
obj.firstName = 'foo';
return obj;
}

顺便说一句(这可能就是你陷入困境的原因),从技术上讲(尽管有 class 关键字),JavaScript 没有类,它有原型(prototype),它们是继承。

关于javascript - 继承Javascript类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44991344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com