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

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

    In other words you want to change prototype (a.k.a. class) of existing object. Technically you can do it this way:

    var Person = {
      function fullName() { return this.firstName + " " + this.lastName; }
    };
    
    // that is your PROFIT function body: 
    personData.__proto__ = Person ;
    

    After that if you will get true on personData instanceof Person

提交回复
热议问题