是否可以用类似C#的JavaScript进行对象初始化

Is it possible to do object initialization in JavaScript similar to C#?

本文关键字:JavaScript 对象 初始化 是否      更新时间:2023-09-26

更具体地说,对于具有两个公共属性的随机类,在C#中,您可以执行以下操作:

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

有可能在JavaScript中做类似的事情吗?我想的是:

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

但我认为它没有按预期工作。或者一个简单的复制功能:

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

因此对象初始化将变为:

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

但是还有一个额外的对象创建。有没有更好的方法来实现这一点?

使用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

对于那些用TypeScript编码的人来说,这里有另一种方法:

创建基类:

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

扩展:

import { BaseClass } from './base.model';
export class Child extends BaseClass<Child > {
    Id: string;
    Label: string;
}

然后你可以做这样的事情:

const child = new Child({
    Id: 1,
    Label: 'My Label'
});
var Point = { /* methods */ };
Object.create(Point, {
    x: { value: 0 },
    y: { value: 0 }
});

当然,这在默认属性初始化方面有点冗长,所以我倾向于使用extend实用程序。

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

对象文字可能是最接近的:

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

没有什么通用的(满足您的要求),但您可以这样做:

function Point( x, y ) {
    this.x = x || 0;
    this.y = y || 0;
}
Point.prototype = { ... };
new Point( 1,2 );