【问题标题】:Construct an object that has member functions from an object that has no member function with their properties are the same?从没有成员函数的对象构造一个具有成员函数的对象,它们的属性是否相同?
【发布时间】:2022-01-20 02:21:39
【问题描述】:

我正在尝试构建一个带有文档数据库的 javascript 应用程序,该文档数据库可以在没有函数成员的情况下存储和检索对象数据(作为 api 提供)。

现在我有一个类,它有许多属性和一些函数作为原型。

Project: function(){
  this.a= 'abc';
  this.f = function(){
    console.log(this.a);
  }
}
//object from the databse
p0 = {
  a: 'abc';
}

我想将一个普通对象转换为一个成员函数可用的对象。

当我尝试这样的事情时,它不会起作用:

// It won't work:
// for it needs a map that have many properties such as writable etc.
var pobj = Object.create(new Project(), p0);

我尝试在互联网上用不同的关键字搜索这个问题,但没有找到相关的。

【问题讨论】:

  • Object.create(new Project(), p0) ------> Object.create(new Project(), Object.getOwnPropertyDescriptors(p0))

标签: javascript object prototype clone


【解决方案1】:

您可能想要使用的函数是Object.assign

因此您可以使用Object.create 创建类的实例(使用原型),然后将数据中的值分配给新实例,然后调用构造函数(确保不覆盖这些值)。

function Project() {
  if (this.foo === undefined) this.a = 'foobar';
  return this;
}

Project.prototype.print = function() {
  console.log(this.foo);
};

var data = {
  foo: 'bar'
};

var obj = Object.create(Project.prototype); // empty instance
obj = Object.assign(obj, data); // copy data
obj = obj.constructor(); // start constructor

obj.print();

或者,您可以使用 new 运算符创建一个新实例,然后分配数据。

function Project() {
  this.a = 'foobar';
  return this;
}

Project.prototype.print = function() {
  console.log(this.foo);
};

var data = {
  foo: 'bar'
};

var obj = Object.assign(new Project(), data);

obj.print();

不相关的注释 使用class.prototype.functionName = function(){...}在函数体外部声明不需要关闭的公共函数通常是个好主意

【讨论】:

  • 谢谢,我会尝试使用原型来定义函数。
猜你喜欢
  • 2012-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多