Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading