Search code examples
javascriptenumerationprototype-programming

rename hasOwnProperty but prevent enumeration


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.


Solution

  • You can only prevent enumeration in ES5 compatible browsers, using Object.defineProperty():

    Object.defineProperty(myObj, "has", { value: Object.prototype.hasOwnProperty });
    

    defineProperty() defaults to setting non-enumerable properties. A better ES3 approach would be to just alias the function and don't stick it on Object.prototype:

    var has = function (ob, prop) { 
        return Object.prototype.hasOwnProperty.call(ob, prop); 
    }
    

    I don't see anything wrong with your own String.prototype.in approach either, except maybe potential naming collisions in the future, but that's your call. Calling it String.prototype.on would remove ambiguity with the in operator.