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

前端 未结 9 1655
故里飘歌
故里飘歌 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 14:54

    You don't need to use prototypes in order to bind a custom method in your barebone object.

    Here you have an elegant example that don't pollute your code avoiding redundant code

    var myobj = {
      title: 'example',
      assets: 
      {
        resources: ['zero', 'one', 'two']
      }
    }
    
    var myfunc = function(index)
    {
        console.log(this.resources[index]); 
    }
    
    myobj.assets.giveme = myfunc
    
    myobj.assets.giveme(1);
    

    Example available in https://jsfiddle.net/bmde6L0r/

提交回复
热议问题