且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我们可以在javascript中将通用对象转换为自定义对象类型吗?

更新时间:2022-04-21 21:49:38

@PeterOlson的答案可能会在今天恢复,但是看起来Object.create已更改. 我会使用@ user166390在评论中说的复制构造方法.
我取消这篇文章的原因是因为我需要这样的实现.

The answer of @PeterOlson may be worked back in the day but it looks like Object.create is changed. I would go for the copy-constructor way like @user166390 said in the comments.
The reason I necromanced this post is because I needed such implementation.

如今,我们可以使用 Object.assign ( @SayanPal解决方案的信用额)& ES6语法:

Nowadays we can use Object.assign (credits to @SayanPal solution) & ES6 syntax:

class Person {
  constructor(obj) {
    obj && Object.assign(this, obj);
  }

  getFullName() {
    return `${this.lastName} ${this.firstName}`;
  }
}

用法:

const newPerson = new Person(person1)
newPerson.getFullName() // -> Freeman Gordon

下面的ES5答案

function Person(obj) {
    for(var prop in obj){
        // for safety you can use the hasOwnProperty function
        this[prop] = obj[prop];
    }
}

用法:

var newPerson = new Person(person1);
console.log(newPerson.getFullName()); // -> Freeman Gordon

使用较短的1.5衬纸:

Using a shorter version, 1.5 liner:

function Person(){
    if(arguments[0]) for(var prop in arguments[0]) this[prop] = arguments[0][prop];
}