How to add methods to a (JSON) object's prototype?

前端 未结 9 1630
故里飘歌
故里飘歌 2020-12-23 14:05

Let\'s say I receive some JSON object from my server, e.g. some data for a Person object:

{firstName: \"Bjarne\", lastName: \"Fisk\"}

Now,

9条回答
  •  旧巷少年郎
    2020-12-23 14:48

    Assuming your Object comes from some JSON library that parses the server output to generate an Object, it will not in general have anything particular in its prototype ; and two objects generated for different server responses will not share a prototype chain (besides Object.prototype, of course ;) )

    If you control all the places where a "Person" is created from JSON, you could do things the other way round : create an "empty" Person object (with a method like fullName in its prototype), and extend it with the object generated from the JSON (using $.extend, _.extend, or something similar).

    var p = { first : "John", last : "Doe"};
    
    function Person(data) {
       _.extend(this, data);
    }
    
    Person.prototype.fullName = function() {
       return this.first + " " + this.last;   
    }
    
    console.debug(new Person(p).fullName());
    

提交回复
热议问题