Cunning Cunning - 2 months ago 9
Javascript Question

Referencing self Object in Object.defineProperties

I am trying to extend the base Object object to include join function for all objects. The code looks like this (obviously not a valid code):

function is_scalar(obj){return (/string|number|boolean/).test(typeof obj);}
Object.defineProperties(Object.prototype, {
"join": {
value: (seperator = " ", recursive = false) => {
var out = [];
Object.keys(Object).forEach((prop) => {
if (Array.isArray(Object[prop])) {
out.push(Object[prop].join(seperator));
}
else if(is_scalar(Object[prop])){
out.push(Object[prop]);
}
});
return out.join(seperator);
},
enumerable: false
}
});


The problem is I don't know how to reference the instance object for the
Object.Keys
clause.

Efforts

I have already tried
this
, but it refers to the
window
object.

I also have tried using
Object
and
Object.prototype
and both look empty.

Answer

Don't use an arrow function.

Object.defineProperties(Object.prototype, {
  "join": {
    value: function (seperator = " ", recursive = false) {
      console.log(this);
    },
    enumerable: false
  }
});


({}).join()