Skip to content

Explanation of "Return Statement" #7 is misleading #92

Open
@ryancwalsh

Description

@ryancwalsh

Thank you so much for your list of helpful questions.

Looking at https://github.com/ganqqwerty/123-Essential-JavaScript-Interview-Questions#7-what-would-be-the-output-of-following-code--2, I think the explanation would make more sense like this:

(function () {
  console.clear();
  function getName1() {
    console.log("getName1", this.name);
  }
  Object.prototype.getName2 = function () {
    console.log("Object.prototype.getName2", this.name);
  };
  Object.prototype.getName3 = () => {
    console.log(
      "Object.prototype.getName3",
      this.name,
      "Why does this one not work?"
    ); //https://stackoverflow.com/a/31755263/470749 because "Arrow functions provide a lexical this. It uses the `this` that is available at the time the function is evaluated." See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
  };
  Object.prototype.getName4 = () => {
    console.log(
      "Object.prototype.getName4",
      Object.getPrototypeOf(this).name,
      "This one does not make sense"
    );
  };
  let personObj = {
    name: "Tony",
    print: getName1
  };
  personObj.print();
  personObj.getName2();
  personObj.getName3();
  personObj.getName4();
})();

Thanks again, and best of luck.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions