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

前端 未结 9 1590
故里飘歌
故里飘歌 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 15:07

    Use the new-ish Object.setPrototypeOf(). (It is supported by IE11 and all the other browsers now.)

    You could create a class/prototype that included the methods you want, such as your fullName(), and then

    Object.setPrototypeOf( personData, Person.prototype );
    

    As the warning (on MDN page linked above) suggests, this function is not to be used lightly, but that makes sense when you are changing the prototype of an existing object, and that is what you seem to be after.

    0 讨论(0)
  • 2020-12-23 15:10

    You should probably not do this.

    JSON allows you to serialize a state, not a type. So in your use case, you should do something like this :

    var Person = function ( data ) {
        if ( data ) {
            this.firstName = data.firstName;
            this.lastName = data.lastName;
        }
    };
    
    Person.prototype.fullName = function ( ) {
        return this.firstName + ' ' + this.lastName;
    };
    
    //
    
    var input = '{"firstName":"john", "lastName":"Doe"}';
    var myData = JSON.parse( input );
    var person = new Person( myData );
    
    0 讨论(0)
  • 2020-12-23 15:12

    I don't think it is common to transport methods with data, but it seems like a great idea.

    This project allows you to encode the functions along with your data, but it is not considered standard, and requires decoding with the same library of course.

    https://github.com/josipk/json-plus
    
    0 讨论(0)
提交回复
热议问题