Can we cast a generic object to a custom object type in javascript?

后端 未结 6 1322
暖寄归人
暖寄归人 2021-01-31 13:46

For example, I already have this object somewhere in the code, it is a generic object:

var person1={lastName:\"Freeman\",firstName:\"Gordon\"};

6条回答
  •  花落未央
    2021-01-31 14:17

    This is just a wrap up of Sayan Pal answer in a shorter form, ES5 style :

    var Foo = function(){
        this.bar = undefined;
        this.buzz = undefined;
    }
    
    var foo = Object.assign(new Foo(),{
        bar: "whatever",
        buzz: "something else"
    });
    

    I like it because it is the closest to the very neat object initialisation in .Net:

    var foo = new Foo()
    {
        bar: "whatever",
        ...
    

提交回复
热议问题