0

Disclaimer: I don't want to use constructors and I don't want to use the keyword new. I want to do this all with Object.create.

Here is the code I have, that works perfectly fine:

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 }

What I would like to do, is create a new object and pass in x and y all in one line. Is this possible?

1
  • 1
    make a function that calls Object.create(), then the other stuff needed to the instance for a one-liner. Commented Mar 27, 2015 at 20:12

3 Answers 3

2

You could use the properties parameter:

Object.create(vectorPrototype, { x: { value: 1 }, y: { value: 1 } })
Sign up to request clarification or add additional context in comments.

2 Comments

This is good. I guess I am confused why I need to specify value. Is this some type of standardized way that this always is done?
yes,this how you define a default value. thats part of the properties you can give tox along with writable, configurable etc.. check this link developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
0

Off the top of my hat:

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

This should work with new as well as without it. That said, I'm not sure if this classifies as "not a constructor" in your point of view.

Comments

-1

You can create object like this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.