Why is this object created based on a class returning undefined? shouldn't it return the 'red'?
this.name='red' // global.name
class foo {
constructor(name){
this.name= name
return function (){
console.log(this.name); // new object is gonna return only this
}
}
}
let oof = new foo ('green');
console.log(oof) //name is not defined. Expected to return 'red' (global)
oof(); //cannot read the property
function color () {
console.log(this.name);
}
color(); //red
thanks!
Edit1: I misswrote the oof. Corrected now.
Edit2: So guys, I know that a constructor usually don't take a return (it wouldn't make sense) and that the this keyword refers to the object that's going to be created. The thing here is that I was trying to test the limits of the this. In a normal function, this.namewould return 'red' as it's called in the global scope. Why it's not working in this case? because it's a function created by a class?
Edit3: To make it clear, I added another function color, which is supposed to be the same as oof (both are functions and called on the window) but refering the globalThis (red). The only difference is the way the are constructed.