Harry Yu Harry Yu - 3 years ago 205
Javascript Question

How to get object itself in custom Object.prototype.xxx function?

Object.prototype.getB = function() {

// how to get the current value a
return a.b;

};
const a = {b: 'c'};
a.getB();


As you can see, I want to make a function to all Object value. And I need to get the object value in this function then do something.

Answer Source

You need this:

Object.prototype.getB = function(){
  return this.b;
};

You get the object itself with the this keyword, which only works like this in a proper function expression, not in an arrow function.


If you really want to mutate the prototype, this is a better way, which makes it non-enumerable and checks for the function’s existence beforehand:

if(!Object.prototype.hasOwnProperty("getB")){
  Object.defineProperty(Object.prototype, "getB", {
    value: function(){
      return this.b;
    }
  })
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download