开发者

Adding the same function to many elements (using js prototypes?)

开发者 https://www.devze.com 2023-01-27 21:20 出处:网络
In my application, I receive a collection of Comments with JSON. Then, I want to add functions to every item in this collection, so for example if a Comment has comment.first_name and comment.last_na

In my application, I receive a collection of Comments with JSON.

Then, I want to add functions to every item in this collection, so for example if a Comment has comment.first_name and comment.last_name, I want to build comment.full_name().

So far, I'm doing:

comment.full_name = function() { return this.first_name+" "+this.last_name }

My question is, since there are many comments (and other methods more complex than this one), how could I use prototypes or constructors to add the same function to every item in the collection, without inserting it into each element?

EDIT:

Here is an example of code:

comments = ({"1": {"first_name":"John", "last_name":"Silver"}, "2": {"first_name":"Jack", "last_name":"Sparrow"}})

Now, I'm looking for something that will return

comments[1].name() 开发者_JS百科//=> John Silver
comments[2].name() //=> Jack Sparrow


To answer your direct question, you attach to an object's prototype by literally attaching it to is prototype chain with the prototype keyword. To attach a function, full_name() to the comment object's prototype, you would do something like this:

comment.prototype.full_name = function () {
  if (typeof(this.first_name) !== "undefined" && typeof(this.last_name) !== "undefined") {
    return this.first_name + " " + this.last_name;
  } else {
    return ""
  }
};

EDIT:

The above code will work for your situation as well. It will attach a property, full_name to each value in your JSON object. full_name is a function. It will return a concatenated string containing the current object's first_name property, a space, and the current object's last_name property, as long as both of the properties are not undefined. If one or both of them are, it will return an empty string.


Given that JSON does not encapsulate any info about type, I'm not sure you could do this generically without adding the method to the object prototype. Whether or not this is desirable is a subject for debate. Once you've got the data from the JSON parser, it's probably better to duck punch the objects one at a time (as it appears you are doing now).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号