1

I'm trying to get the following code to work.

Array.prototype.test = {
    func: function() {
        console.log(this);
        return this;
    }
};

Then when I run the following.

[].test.func();

The problem is the this within that function is the object Array.prototype.test NOT the array that I passed in.

I feel like there has to be way to do this without setting Array.prototype.test to a function and having to call it like so [].test().func();.

Chai uses this type of syntax quite a bit. So I'm assuming it's possible.

How can I get this to work as I'm expecting it to?

Charlie Fish
  • 18,491
  • 19
  • 86
  • 179
  • why not Array.prototype.test = function() { console.log(this); return this; } – xianshenglu Apr 01 '18 at 03:19
  • @xianshenglu I mentioned this in my question. Because I have seen it done the other way, so I'm pretty sure it's possible. Chai is a great example of that. In my opinion the syntax of what I'm trying to achieve is a lot cleaner, and meets my needs better. It's also meant to be a learning experience, and not taking the cheap way out by trying to explore a new method of doing it. – Charlie Fish Apr 01 '18 at 03:26

1 Answers1

4

JavaSript doesn't really have a good way to access that.

You could use a getter for test that returns a function with bound methods.

Object.defineProperty(Array.prototype, 'test', {
  configurable: true,
  enumerable: false,
  get: function() {
    return {
      func: function() {
        console.log(this);
        return this;
      }.bind(this)
    };
  }
});

[].test.func();

But it's pretty convoluted compared to just using .testFunc.

// Using Object.defineProperty to avoid enumerable prototype properties.
Object.defineProperty(Array.prototype, 'testFunc', {
  configurable: true,
  enumerable: false,
  writable: true,
  value: function() {
    console.log(this);
    return this;
  }
});

[].testFunc();

See How does the expect().to.be.true work in Chai? to see they do roughly the same thing.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • Great detail and explanation. Really appreciate the through answer. And yes, I totally can see how it's more convoluted, but still great to understand the inner workings of JS a bit more and such. Thanks! – Charlie Fish Apr 01 '18 at 03:34