Object.prototype.in // a quick hack

Object.prototype.in = function(a) {
if (typeof a == “string”) return this.hasOwnProperty(a);
for (var k in this) { if (this.hasOwnProperty(k)) { a(k,this); } }
}

 

A quick hack for what?

var o = { a: 1, b: 2, c: 3 };

if (o.in(“a”)) alert(‘a is in o’);
o.in(function(key,o) { console.log(‘do something with o[key]’ + o[key]); });

Perhaps these methods would be more useful. Be careful though extending Object can have undesirable side effects due to code not using hasOwnProperty()

Object.prototype.has = function(p) { return this.hasOwnProperty(p); }
Object.prototype.get = function(p) { if (this.hasOwnProperty(p)) return this[p]; }
Object.prototype.foreach = function(cb) { for (var k in this) if (this.has(k)) cb(k,this); }

Advertisements

About austinfrance

Technical Developer @ RedSky IT / Explorer Software
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s