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

前端 未结 9 1631
故里飘歌
故里飘歌 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

    If you're dealing with plain JSON data then the prototype of each person object would simply be Object.prototype. In order to make it into an object with a prototype of Person.prototype you'd first of all need a Person constructor and prototype (assuming you're doing Javascript OOP in the traditional way):

    function Person() {
        this.firstName = null;
        this.lastName = null;
    }
    Person.prototype.fullName = function() { return this.firstName + " " + this.lastName; }
    

    Then you'd need a way to turn a plain object into a Person object, e.g. if you had a function called mixin which simply copied all properties from one object to another, you could do this:

    //example JSON object
    var jsonPerson = {firstName: "Bjarne", lastName: "Fisk"};
    
    var person = new Person();
    mixin(person, jsonPerson);
    

    This is just one way of solving the problem but should hopefully give you some ideas.


    Update: Now that Object.assign() is available in modern browsers, you could use that instead of writing your own mixin function. There's also a shim to make Object.assign() work on older browsers; see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill.

提交回复
热议问题