0

I expected this javascript code to print "a". This javascript code prints "b".

function newA() {
 this.doSomething = function() {console.log("a");}
 return this;
}

function newB() {
 this.doSomething = function() {console.log("b");}
 return this;
}

const a = newA();
const b = newB();
a.doSomething();
test.js:7 b

It still prints "b" if the order that newA and newB are declared in is switched.
I don't know why this is happening and I can't phrase my problem well enough to Google an explanation.

blex
  • 24,941
  • 5
  • 39
  • 72
rbxb
  • 11
  • 3
  • The way you call the functions, `this` refers to the global object. You are basically creating a global variable `doSomething`. The second function call will always override that variable. `a === window`. If you put your code into strict mode you would get an error. You are not actually using the functions as "classes". – Felix Kling Jan 17 '20 at 22:22
  • Try `new newA()` and `new newB()` to see the expected behaviour .... – Jonas Wilms Jan 17 '20 at 22:22

0 Answers0