0

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.

Tala
  • 909
  • 10
  • 29
  • 1
    You should use an arrow function for something like `is_scalar`, but not for methods! Why not use a simple method shorthand (drop the `:` and the `=>` and it'll work)? – Bergi Sep 23 '16 at 00:22

1 Answers1

1

Don't use an arrow function.

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


({}).join()
Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
Hamms
  • 5,016
  • 21
  • 28
  • Thanks a lot! Here's my final working test fiddle, just in case. https://jsfiddle.net/epm3od0x/13/ – Tala Sep 23 '16 at 00:07