Home > Net >  Javascript OOP : Explain why f.a returns something whereas f.b and c.a returns undefined
Javascript OOP : Explain why f.a returns something whereas f.b and c.a returns undefined

Time:07-10

Explain why f.a returns something whereas f.b and c.a returns undefined. Don't answer : because it's like that or you don't really understand javascript and learn by rotte as Feynman says ;)

function f() {
  f.a = "test 1";
  this.b = "test 2";
  return this;
}

let c = f();
console.log(f.a);
console.log(f.b);
console.log(c.a);

CodePudding user response:

After you call f, it gives itself (f the Function object) a property of a assigned to the string "test 1".

Because f is not called with new, this inside the function body refers to the global object (window in the browser, global in node). This means the assignment to this.b inside the function body is equivalent to window.b = "test 2".

Then the function f returns this, which is the global object, so c = global.

The global object hasn't been assigned a property a, so c.a is undefined. But c.b would be "test 2"

CodePudding user response:

f.a returns something, because in the function you assign "test 1" to f.a

this.b is the window console.log(window.b) will return "test 2"

c is the return of the function you return "this" and "this" is the window -> the property a of the window is undefined

  • Related