4

More specifically, for a random class with two public properties, in C# you can do something like this :

new Point() {
   Y = 0,
   X = 0
}

Is it possible to do something similar in JavaScript? I was thinking of something along the line of :

{
   prototype : Object.create(Point.prototype),
   X : 0,
   Y : 0
}

but I don't think it works as intended. Or a simple copy function :

function Create(object, properties) {
    for (p in properties)
        object[p] = properties[p];

    return object;
}

so the object initialization would become :

Create(new Point(), {X : 0, Y : 0});

but there is an extra object creation. Is there a better way of achieving this?

2
  • 3
    What are you trying to achieve (in terms of functionality)? Javascript is not C#. Commented Jan 20, 2012 at 20:24
  • Copying the prototype of Point into a new object, while initializing different properties of that object. Commented Jan 20, 2012 at 20:27

5 Answers 5

3

Using ES7:

class Point {
  x = 0;
  y = 0;
}

// {x: 5, y: 10}
const p = {...new Point(),  x: 5, y: 10 };

https://codepen.io/anon/pen/WaLLzJ

Sign up to request clarification or add additional context in comments.

1 Comment

This solution shouldn't be used since the Point prototype is lost when using spread operator.
2

For those who code in TypeScript, here is another way to do it:

Create a base class:

export class BaseClass<T> {
    constructor(data?: Partial<T>) {
        Object.assign(this, data);
    }
}

Extend it:

import { BaseClass } from './base.model';

export class Child extends BaseClass<Child > {
    Id: string;
    Label: string;
}

Then you can do something like this:

const child = new Child({
    Id: 1,
    Label: 'My Label'
});

1 Comment

Welcome to SO! Could you please edit your question and explain a bit more what you are doing, i.e. why your solution works.
1
var Point = { /* methods */ };

Object.create(Point, {
    x: { value: 0 },
    y: { value: 0 }
});

Of course that's a bit verbose on the default property initialization so I tend to use an extend utility.

extend(Object.create(Point), {
    x: 0,
    y: 0
});

Comments

1

Object literals are probably the closest:

var point = {
    X: 0,
    Y: 0
};

1 Comment

But this method does not copy the prototype of Point. That is the dilemma.
0

Nothing general (that meets your requirements) but you could do this:

function Point( x, y ) {
    this.x = x || 0;
    this.y = y || 0;
}

Point.prototype = { ... };

new Point( 1,2 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.