gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:00:31 25 4
gpt4 key购买 nike

例如,我在代码的某处已经有了这个对象,它是一个通用对象:

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

我有一个 Person 对象的构造函数:

function Person(){
this.getFullName=function(){
return this.lastName + ' ' + this.firstName;
}
}

是否有一个简单的语法允许我们将 person1 转换为 Person 类型的对象?

最佳答案

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 语法:

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 衬垫:

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

jsfiddle

关于javascript - 我们可以在 javascript 中将通用对象转换为自定义对象类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8736886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com