123-Essential-JavaScript-Interview-Questions icon indicating copy to clipboard operation
123-Essential-JavaScript-Interview-Questions copied to clipboard

Explanation of "Return Statement" #7 is misleading

Open ryancwalsh opened this issue 4 years ago • 0 comments

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.

ryancwalsh avatar May 11 '20 12:05 ryancwalsh