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

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

    Anonymous objects don't have a prototype. Why not just have this:

    function fullName(obj) {
        return obj.firstName + ' ' + obj.lastName;
    }
    
    fullName(person);
    

    If you absolutely must use a method call instead of a function call, you can always do something similar, but with an object.

    var Person = function (person) { this.person = person; }
    Person.prototype.fullName = function () {
        return this.person.firstName + ' ' + this.person.lastName;
    }
    var person = new Person(personData);
    person.fullName();
    

提交回复
热议问题