Search code examples
javascriptpolyfillshasownproperty

Javascript HasOwnProperty Polyfill


I know this may sound like an absurd, unnecessary question, but it really isn't.

https://caniuse.com/?search=Hasownproperty shows 100% of tracked desktop clients support, which is as you would expect. But switching to tracked mobile clients shows a shocking mere 95.4% support, which given that mobile clients are even with or even outstripping desktop ones, means an extrapolation of around 2.5% of all current clients visiting a webpage DON'T support hasOwnProperty natively.

Given that a large amount of third-party libraries including jQuery, Modernizr, and Crockford’s json2.js reference hasOwnProperty and do not polyfill it, it's really quite important to polyfill this.

I am looking for a way to polyfill hasOwnProperty according to the spec. It can be shallowly polyfilled (albeit incorrectly) using a for in loop, but that won't return false for inherited properties.


Solution

  • Please check polyfill section of object.hasOwnProperty

    This is the implementation

    (function(w){
    var isFunction=w.isFunction||(w.isFunction=function(x){return typeof(x)==='function'}),
    has=w.has||(w.has=function(o,p){var e=p in o;return {value:e && (e=o[p]) && true,refer:e,valueOf:function(){return this.value}}}),
    Polyfill=w.PolyfillMethod||(w.PolyfillMethod=function(o,p,x){var e=has(o,p);if(e && (e=isFunction(e.refer))===false){o[p]=x};return e}),
    theProto=w.Object.prototype;
    
    Polyfill(theProto,'hasOwnProperty',function(x){var o,e=this,p=String(x);return p in e && (o=e.__proto__||e.constructor.prototype,(p in o ===false)||e[p]!== o[p])});
    
    })(window);