0

If I use the first representation, the console will log the name, however in the second one it does output "JS Bin Output", any idea what happened?

let person = {
  name: 'Fred',
  sayMyName: function(params) {
    return (this.name);
  },
};

let obj = person;
person = null;
let sayMyName = obj.sayMyName;
console.log(obj.sayMyName()); // logs `Fred`
console.log(sayMyName()); // logs `JS Bin Output`
mka1
  • 39
  • 1
  • 3
  • Calling `sayMyName();` will log `window.name` (which appears to be some sort of uuid in StackOverflow snippets), not `undefined`. In strict mode, it will throw a `cannot access property name of undefined` exception. Try `let sayMyName = obj.sayMyName.bind(person);` – connexo Jan 25 '22 at 10:34
  • Please note the change in my code – mka1 Jan 25 '22 at 11:13
  • For what reason are you nulling `person`? – connexo Jan 25 '22 at 11:50
  • wouldn’t I still get the same output if I removed that line? – mka1 Jan 25 '22 at 13:19
  • Yes, that's why I am asking. What's your thought in assigning null there? – connexo Jan 25 '22 at 13:34
  • Commenting that line out didn't change the output unfortunately, I feel like I am missing something about the "this" value. – mka1 Jan 25 '22 at 14:14
  • Check the links in the duplicate notification above your post, especially https://stackoverflow.com/questions/30486345/losing-this-context-in-javascript-when-passing-around-members – connexo Jan 25 '22 at 16:21
  • @mka1 The `person = null;` line has nothing to do with the `this` behavior. The `this` behavior is explained in each of the linked posts. That issue should be solved. What we’re additionally asking _now_ is: why _did_ you put `person = null;` there? What did you hope this would achieve? – Sebastian Simon Jan 26 '22 at 01:25

0 Answers0