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

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

提交回复
热议问题