我们可以在javascript中将通用对象转换为自定义对象类型吗? [英] Can we cast a generic object to a custom object type in javascript?
问题描述
例如,我在代码中的某个位置已经有此对象,它是一个通用对象:
For example, I already have this object somewhere in the code, it is a generic object:
var person1={lastName:"Freeman",firstName:"Gordon"};
我有一个Person对象的构造函数:
I have the constructor for a Person object:
function Person(){
this.getFullName=function(){
return this.lastName + ' ' + this.firstName;
}
}
有没有简单的语法可以让我们将person1转换为Person类型的对象?
Is there a simple syntax that allows us to convert person1 to an object of type Person?
推荐答案
@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];
}
这篇关于我们可以在javascript中将通用对象转换为自定义对象类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!