Search code examples
javascriptfunctionpropertiesundefinedbind

JavaScript: *Can* set property of undefined with call / apply / bind?


I think I just discovered a new weird thing about JavaScript.

Does someone know how exactly this happens?

let test;

function setProp() {
  this.prop = 42;
}
setProp.call(test);

// No error yet?
// So 42 should be saved inside test.prop?

// Though test=undefined?

console.log(test);
try {
  console.log(test.prop);
} catch (e) {
  console.log(e.message);
}

// -> undefined
// -> Cannot read property 'prop' of undefined
// Ok, indeed

function getProp() {
  console.log(this.prop);
}
getProp.call(test);

// -> 42
// Wait, what?

I'm just curious :)


Solution

  • In non-strict mode, passing undefined as the first argument to .call() implies that you want it to be the global object (like window).

    Try your test with "use strict"; at the top and see if that makes a difference.