R
R
roskoshinsky2016-04-19 13:53:16
JavaScript
roskoshinsky, 2016-04-19 13:53:16

How to add a method to a standard JavaScript object?

Hey! I add a method to the standard Object JavaScript object via Object.prototype. However, after that, it becomes one of the properties of any object that appears during iteration (for in), while hasOwnProperty, of course, does not save. How to make the method "hidden" during iteration, not revealed as a property?

if(Object.prototype.flip === undefined){
  (function(){
    Object.prototype.flip = function(bSelf){
      if(bSelf === undefined || bSelf){
        for(var k in this)if(this.hasOwnProperty(k)){
          this[this[k]] = k;
          delete this[k];
        } // fr
        return this;
      } else {
        var oObject = this;
        return oObject.flip();
      } // if
    }; // flip
  })();
} // if

var oObject = {1:"a", 2:"b", 3:"c"};
for(var k in oObject)if(oObject.hasOwnProperty(k)){
  log(k); // a, b, c, flip
} // fr

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
NaN, 2016-04-19
@roskoshinsky

Object.defineProperty(Object.prototype, 'flip', {

   value: function(){},
   enumerable: false,

});

R
roskoshinsky, 2016-04-19
@roskoshinsky

Colleagues, I made a mistake in the given code example, it is clear that instead of this there should have been oObject. But most importantly, I did not specify that we are talking about Google Script and in it the method is visible when listing properties. However, the NaN solution helped. The only thing is that the first argument is not Object a Object.prototype. Thank you NaN!

M
Maa-Kut, 2016-04-19
@Maa-Kut

hasOwnProperty saves itself quite well, you just need to call it not on this , but on oObject .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question