I’m having to use hasOwnProperty a lot in my code and it is annoyingly long and camel-cased to type. I wanted to be able to just say myObj.has('x'), but when I tried to make an alias for hOP in the Object.prototype ‘has’ now gets enumerated in for..in loops. What is the best way to get what I want? I mean I could just make a global function that works like has(obj, prop) but I like the dot format better and I would like to know what tricks javascript might have up it’s sleeve, so I am looking for suggestions.
Update: this seems pretty hacky but is String.prototype.in = function(obj){return obj.hasOwnProperty(this)} OK? With that I can then say if ( 'x'.in(myObj) ) {... Unfortunately it adds another layer of function call rather than just aliasing hasOwnProperty, but I like the syntax.
You can only prevent enumeration in ES5 compatible browsers, using
Object.defineProperty():defineProperty()defaults to setting non-enumerable properties. A better ES3 approach would be to just alias the function and don’t stick it onObject.prototype:I don’t see anything wrong with your own
String.prototype.inapproach either, except maybe potential naming collisions in the future, but that’s your call. Calling itString.prototype.onwould remove ambiguity with theinoperator.