从一个没有成员函数的对象构造一个具有成员函数的对象,它们的属性是否相同?

Construct an object that has member functions from an object that has no member function with their properties are the same?

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

现在我有一个 class,它有许多属性和一些功能作为原型。

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.assign

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

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(){...}

在函数体外部声明不需要闭包的 public 函数通常是个好主意