DEV Community

Discussion on: Understanding This, Bind, Call, and Apply in JavaScript

Collapse
 
zanehannanau profile image
ZaneHannanAU

May as well do it:

  • call moves the hidden this to a self parameter (ie: rust).
  • apply moves the parameters tuple list to a tuple or fixed array.
  • bind moves the hidden this to a self and creates a context using it.
  • this is the object it was called upon; or undefined in toplevel strict mode.
  • arrow functions consume only arguments and context, and do not have a this context of their own. In rust the closest is a closure with move. This is normal.

These can be composed in insane ways:

const fbind = fn => Function.prototype.call.bind(fn);

In this case, I move the this hidden parameter into the self leading parameter. I use this a lot actually... my typescript for it is

export declare const fbind: <F extends (this: T, args: any[]) => R, T, R>(fn: F) => (self: T, ...args: Parameters<F>) => R;

Furthermore, including Reflect and Proxy:

  • Reflect.apply adds a dynamic dispatcher (function) option.
  • Reflect.construct adds a class dispatcher (class/new) option.
  • Proxy { apply() {} } is the inverse of Reflect.apply; and can be heavily reused in children.
  • same in Proxy { construct() {} }

Adding getters and setters:

  • get a() {} returns some value representing a; which may be a constant or variable or an internal value. This can also have side effects...
  • set a(val) {} returns void (undefined) and sets a; or else throws when there's some issue with val. For example, checking Number.isInteger(val) and throwing when it fails. Side effects allowed here as well...