0

How can I get the reference to what's being return to the method call? Like how we have the arguments variable to get all arguments being passed to a function. How can I get what's being returned to so I can chain a function?

let myFunc = function(obj, num){
  if (typeof obj === 'number' && typeof num === 'undefined') {
    num = obj;
    obj = this;
  }
  console.log(obj.name);
  console.log(num);
  console.log(Object(this));
  return obj;
};

let myObj = {
  name: 'Devin',
};

myFunc(myObj, 1);

myObj.myFunc = myFunc;

myObj.myFunc(2).myFunc(3);

edit: It's written out this because it's currently used in many places that I will have to refactor down the road but do not have time to right now. So I'm trying to do a few changes that don't affect current code but will work the way I want moving forward. myFunc(myObj, 1) is current but I have done a minor refactor to inline like so... myObj.myFunc(myObj, 2).myFunc(myObj, 3) ... but I thought I could remove myObj as an argument since it's being returned.

edit 2: Changed arrow es6 function to using function keyword to keep this context and added console.log(Object(this)). But still getting undefined from myObj.name and Object(this) only gives the argument

ANSWER: The problem was that I was using an arrow function and that I had typeof num === 'number' instead of equal to 'undefined'. Thank you.

1 Answers1

0

myFunc.bind(myObj) doesn't serve any good purpose because arrows cannot be bound. In order to use dynamic this it should be regular function, e.g. shorthand syntax:

let myObj = {
  name: 'Devin',
  myFunc(num) {
    console.log(num);
    return this;
  }
};

myObj.myFunc(2).myFunc(3); // basically a noop
Estus Flask
  • 206,104
  • 70
  • 425
  • 565