So, from what I understood in the Javascript lesson, I expect the following code that I wrote:
var pro = "I am good at " + this.name + ".";
var football = {
name: "Football",
pro: pro
};
var basketball = {
name: "Basketball",
pro: pro
};
console.log(football.pro);
console.log(basketball.pro);
To output:
I am good at Football.
I am good at Basketball.
But instead it outputs
I am good at undefined.
I am good at undefined.
I don’t really understand what’s wrong. I defined the variable “pro” right above, why is it “undefined”?
But I thought that pro: pro means pro: "I am good at " + this.name + "." which again means pro: "I am good at " + football.name + "." which therefore means "I am good at Football." (same thing applying to basketball)
it won’t work with functions, only with methods (functions inside objects)
that might a bit of a lie, but the truth is very complicated. Javascript is used in the browser, by default this refers to the window object (browser window, the only you are looking at while reading this reply)
const pro = "I am good at " + this.name + ".";
let football = {
name: "Football",
pro: function() {
return pro
}
};
let basketball = {
name: "Basketball",
pro: function() {
return pro
}
};
console.log(football.pro());
console.log(basketball.pro());
^ It still doesn’t work like that, but I noticed that it works like this:
let football = {
name: "Football",
pro: function() {
return "I am good at " + this.name + "."
}
};
let basketball = {
name: "Basketball",
pro: function() {
return "I am good at " + this.name + "."
}
};
console.log(football.pro());
console.log(basketball.pro());
Which clearly means that the code is rejecting the use of an external variable inside my method, I have no clue why.
const pro = "I am good at " + this.name + ".";
console.log(pro)
the code execute from top to bottom (with the exception of course of functions) so this.name has to be interpreted when you declare the variable
at this point in time, this.name is undefined. When you add it later to your method, the damage is already done
you could do:
function pro(){
return "I am good at " + this.name + ".";
}
let football = {
name: "Football",
}
football.pro = pro
console.log(football.pro())
how Javascript handles this is complicated, i am not entirely sure i understand it myself
the two possible explanations would be: when defined in a function, this doesn’t need a value yet. Given functions execute when called, which we didn’t, so it can have undefined variables in there
or when we add the function as method to the object, this gets re-evaluated or something. I am not sure how Javascript handles this