Javascript构造函数-使用对象? [英] Javascript constructor - Use an object?

查看:41
本文介绍了Javascript构造函数-使用对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用已制成的对象来创建新对象。这就是我要达到的目标:

I'm trying to create a new object by using an already made object. This is what I am trying to achieve:

var obj = {"Name" : "Patrick", "Age": 25, "Country": "US"};
document.writeln(JSON.stringify(obj) + "<br />");

function Person(name, age, country) {
    this.name = name;
    this.age = age;
    this.country = country;
}

document.writeln(JSON.stringify(new Person(obj)));

https://jsfiddle.net/dotjz9tb/

如您所见,我正在尝试创建一个名为Patrick的新人,年龄25岁,碰巧住在美国。我的 Person 构造函数将名称,年龄和国家作为参数。但是,我的对象已经由上一个函数创建,因此我想做 new Person(obj),它将基于<$ c $创建一个新对象c> obj 的参数。

As you can see, I am trying to create a new person called Patrick, aged 25, who happens to live in the US. My Person constructor takes a name, an age, and a country as parameters. However, my object has already been created from a previous function, so I would like to do new Person(obj) and it would create a new object based on obj's parameters.

我知道我可以做 New Person(obj.name,obj.age ,obj.country),但是我宁愿通过构造函数传递一个对象,同时仍然能够执行 new Person( Jack,52, UK)

I know I can do new Person(obj.name, obj.age, obj.country) but I would rather pass the constructor an object instead, while still being able to do new Person("Jack", 52, "UK").

这可能吗?现在,这就是它的真正创建方式:

Is such thing possible? Right now this is how it's really being created:

new Person(obj, undefined, undefined);
//or
{
    "name": {
        "Name":" Patrick","
         Age":25,
        "Country":"US"
    }
}

意思是 age country 设置为空,而 name 设置为我的对象。

Meaning that age and country is set to nothing, while name is set to my object.

推荐答案

您在这里有很多选择。

例如,您可以使您的 Person 在接受的参数上具有多态性。

For example you could make your Person polymorphic on arguments it takes.

function Person(name, age, country) {
   if(arguments.length === 1 && typeof name === 'object') {
      var data = arguments[0];
      name = data.name; //etc
   } 
   //the rest of ctor code goes here
}

更好使用工厂函数并尽可能简化构造函数代码

Or BETTER use factory function and keep your constructor code as simple is possible

function copyPerson(obj) {
   return new Person(obj.name, obj.age, obj.country);
}

//or even
Person.copy = function(obj) {
   return new this(obj.name, obj.age, obj.country)
}

这篇关于Javascript构造函数-使用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆