在javascript中将普通对象强制转换为函数实例(“类”) [英] Casting plain objects to function instances ("classes") in javascript

查看:95
本文介绍了在javascript中将普通对象强制转换为函数实例(“类”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  function Person(){
var self = this;

self.personName =;
self.animals = [];
}

function Animal(){
var self = this;

self.animalName =;
self.run = function(meters){
.....
}
}

服务器响应:

  [{personName:John,animals:[{animalName: cheetah},{animalName:giraffe}]},{personName:Smith,animals:[{animalName:cat},{animalName:dog}]}] 

我从服务器获取Person数组。我想将通用的Person数组转换为typed Person数组。所以我可以使用

  persons [0] .Animals [2] .Run 

我创建了Javascript的

  Object.create(Person,person1); 

但我想要跨浏览器版本的数组支持

  ObjectArray.create(Person,persons); 

  Object.create(Person [],persons); 


解决方案

在JavaScript中创建对象需要调用其构造函数。所以,首先,你将需要找到正确的参数,这可能不总是只是属性。之后,您可以将JSON解析对象中的所有公共属性重新分配给创建的实例。



一般解决方案是每个构造函数接受看起来像实例的任何对象(包括实例)并克隆它们。



或者甚至比重载构造函数更好的方法是在你的类上创建一个静态方法它接受对象并从中创建实例:

  Person.fromJSON = function(obj){
//自定义代码,适用于Person实例
//可能调用`new Person`
return ...;
};






你的情况很简单, t有任何参数,只有公共属性。要将 {personName:John,animals:[]} 更改为对象实例,请使用:

  var personLiteral = ... // JSON.parse(...); 
var personInstance = new Person();
for(var prop in personLiteral)
personInstance [prop] = personLiteral [prop];

您也可以使用 Object.extend 如果你有一个可用的(例如jQuery):

  var personInstance = $ .extend(new Person(),personLiteral ); 

创建 Animal 实例。



由于JSON不传输有关类的任何信息,因此您必须先知道结构。在你的情况下,它将是:

  var persons = JSON.parse(serverResponse); 
for(var i = 0; i< persons.length; i ++){
persons [i] = $ .extend(new Person,persons [i]);
for(var j = 0; j< persons [i] .animals; j ++){
persons [i] .animals [j] = $ .extend(new Animal,persons [i] .animals [j]);
}
}

Btw, / code>方法似乎可能被添加到 Animal.prototype 对象而不是每个实例。


function Person() {
      var self = this;

      self.personName="";
      self.animals=[];
}

function Animal(){
     var self=this;

     self.animalName="";
     self.run=function(meters){
         .....
     }
}

Server response:

 [{personName:John,animals:[{animalName:cheetah},{animalName:giraffe}]} , {personName:Smith,animals:[{animalName:cat},{animalName:dog}]} ]

I'm getting Person array from server. I want to cast generic Person array to typed Person array. So I can use

 persons[0].Animals[2].Run();

I founded Javascript's

 Object.create(Person,person1);

But I want cross-browser version of it with array support

  ObjectArray.create(Person,persons);

or

 Object.create(Person[],persons);

解决方案

Creating an object in JavaScript requires the invocation of its constructor. So, at first you will need to find the correct arguments, which may not always be just properties. After that, you can reassign all public properties from the JSON-parsed object to the created instances.

A general solution would be that every constructor accepts any objects that look like instances (including real instances) and clones them. All the internal logic needed to create proper instances will be located in the right place then.

Or even better than overloading the constructor might be to create a static method on your class that takes objects and creates instances from them:

Person.fromJSON = function(obj) {
    // custom code, as appropriate for Person instances
    // might invoke `new Person`
    return …;
};


Your case is very simple, as you don't have any arguments and only public properties. To change {personName:John,animals:[]} to an object instance, use this:

var personLiteral = ... // JSON.parse("...");
var personInstance = new Person();
for (var prop in personLiteral)
    personInstance[prop] = personLiteral[prop];

You can also use Object.extend functionality for this, should you have one available (e.g. jQuery):

var personInstance = $.extend(new Person(), personLiteral);

The creation of the Animal instances works analogous.

As JSON does not transport any information about the classes, you must know the structure before. In your case it will be:

var persons = JSON.parse(serverResponse);
for (var i=0; i<persons.length; i++) {
    persons[i] = $.extend(new Person, persons[i]);
    for (var j=0; j<persons[i].animals; j++) {
        persons[i].animals[j] = $.extend(new Animal, persons[i].animals[j]);
    }
}

Btw, your run methods seems likely to be added on the Animal.prototype object instead of each instance.

这篇关于在javascript中将普通对象强制转换为函数实例(“类”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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