使用参数创建对象

Object.create with arguments

本文关键字:创建对象 参数      更新时间:2023-09-26

免责声明:我不想使用构造函数,也不想使用关键字new。我想用Object.create.来完成这一切

这是我的代码,工作非常好:

var vectorPrototype = {
    x: null,
    y: null
} 
var v1 = Object.create(vectorPrototype)    // line 6
v1.x = 1
v1.y = 1
console.log(v1);
// { x: 1, y: 1 }

我想做的是创建一个新的对象,并在一行中传递x和y。这可能吗?

您可以使用属性参数:

Object.create(vectorPrototype, { x: { value: 1 }, y: { value: 1 } })

摘得桂冠:

function Vector(x, y)  {
   var prototype = {
    x: null,
    y: null
  } ;
  var ret = Object.create(prototype);
  ret.x = x;
  ret.y = y;
  return ret;
}

这应该与new一起使用,也可以不使用它。也就是说,我不确定在你的观点中,这是否属于"非构造函数"。

您可以创建这样的对象:

var v1 = {x:1, y:1};