0

I am trying to inherit the function context without binding it. Is that possible.

Look below

const test = {
  prop: 42,
  func: function() {
    return this.prop;
  },
};
const fn = test.func;
console.log(fn()) // this show undefined;

console.log(test.func()) // this show 42;

console.log(fn.bind(test)()) // this show 42, I dont like it though;

Why dose not fn inherit the context?

Alen.Toma
  • 4,684
  • 2
  • 14
  • 31
  • 1
    Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – yqlim Feb 15 '22 at 13:14
  • `const fn = test.func.bind(test)` - In a naive way you can think of `this` being a secret argument passed to functions which is defined by the object before the dot. In `test.func()` the `this` is `test`. Whereas with `func()` the `this` is undefined or the window/global object. – evolutionxbox Feb 15 '22 at 13:15
  • It doesn't automatically "inherit" the context because that is how JavaScript works. I understand that `.bind()` is a little messy, but it really is the way to do it. – Pointy Feb 15 '22 at 13:17
  • What you did is basically `cosnt fn = function() { return this.prop; }`. This function knows nothing about any other object, it just takes current context which is `window` – Sergiy Ostrovsky Feb 15 '22 at 13:20
  • "_Why dose not fn inherit the context?_" Because JS obejcts don't have any "context" or "parent". Objects are freely allocated to the memory, and any object property or a variable can refer to an object (functions are also objects). – Teemu Feb 15 '22 at 13:21

0 Answers0