javascript - 在环回中使用原型(prototype)创建实例方法时出现问题

标签 javascript node.js prototype loopbackjs strongloop

我有两个模型,ModelA和ModelB。模型B包含以下属性:

"properties": {
    "firstname": {
      "type": "string",
      "required": true
    },
    "middlename": {
      "type": "string"
    },
    "lastname": {
      "type": "string"
    }
  }

我在ModelB中创建了一个Instance方法,如下所示:

ModelB.js
'use strict';

module.exports = function(ModelB) {
  ModelB.prototype.getFullName = function() {
    console.log(this); // Display result output shown below
  }
};

I have the following result in ModelA

someTestVariable:
   { id: 'e0a844e4-6c8a-489a-8bd6-1d62267d311e',
     firstname: 'Thomas',
     middlename: '',
     lastname: 'Henry' 

   }

我试图从ModelA调用ModelB中的实例方法
ModelB.prototype.getFullName();

此关键字输出以下
ModelConstructor {
  firstname: [Getter/Setter],
  middlename: [Getter/Setter],
  lastname: [Getter/Setter],
  id: [Getter/Setter],
  getFullName: [Function],
  save: [Function],
  isNewRecord: [Function],
  getConnector: [Function],
  destroy: [Function],
  delete: [Function],
  remove: [Function],
  setAttribute: [Function: setAttribute],
  updateAttribute: [Function: updateAttribute],
  setAttributes: [Function: setAttributes],
  unsetAttribute: [Function: unsetAttribute],
  replaceAttributes: [Function],
  patchAttributes: [Function],
  updateAttributes: [Function],
  reload: [Function: reload] 
  }

我不确定如何从ModelA获取ModelB中的名字,中间名和姓氏数据。
任何帮助将非常感激。

最佳答案

定义原型方法如下:

ModelB.prototype.getFullName = function() {
    return this.firstname;
}

// Call instance method by creating Model instance first.

let firstNameData = new ModelB(yourObjectDataFromModelA);

// Then call prototype function

firstNameData.getFullName();

希望这能消除您的疑问。

有关更多信息,请参考以下回送文档:https://apidocs.strongloop.com/loopback-datasource-juggler/v/1.0.0/#manually-add-methods-to-the-model-constructor

关于javascript - 在环回中使用原型(prototype)创建实例方法时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56407022/

相关文章:

javascript - 具有动态名称的 Angular 验证表单

javascript - 如何将日期从 2018-04-29 格式转换为 29 Apr,2018 格式?

javascript 对象原型(prototype)属性访问

javascript - object.key = fn() 和 object.prototype.key = fn() 的区别?

javascript - 从点击事件中删除函数

javascript - 文本淡入淡出循环页面加载后?

JavaScript匿名函数模拟lambda演算中的算术,结果返回 `undefined`

javascript - 如何检索 Express 上的重音字符?

javascript - 无法读取 node/express JS 中未定义的 FindAll() 属性,现有 mySQL DB

c++ - C++ 中的原型(prototype)