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

后端 未结 6 1395
暖寄归人
暖寄归人 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:18

    This borrows from a few other answers here but I thought it might help someone. If you define the following function on your custom object, then you have a factory function that you can pass a generic object into and it will return for you an instance of the class.

    CustomObject.create = function (obj) {
        var field = new CustomObject();
        for (var prop in obj) {
            if (field.hasOwnProperty(prop)) {
                field[prop] = obj[prop];
            }
        }
    
        return field;
    }
    

    Use like this

    var typedObj = CustomObject.create(genericObj);
    

提交回复
热议问题