Reputation: 31
I'm new to JS so apologies for this possibly stupid question. I'm learning about object constructor syntax but I'm confused about why the console log won't show the result of a function that is part of that object. Here is the code:
var sportsCar = {
name: "Lamborghini",
color: "red",
horsepower: "100mph",
electric: true,
showModelName: function() {
return(this.name);
console.log(this.name);
}
};
The result after inputting this object into the developer tool was blank when I thought it would say "Lamborghini." I thought about putting the console.log(showModelName) outside of the object but remembered the function is not globally scoped. Can anyone explain why the console log doesn't show the name?
Upvotes: 3
Views: 35
Reputation: 11
sportsCar.showModelName()
If you change the order of the return statement and console log, this is what you would get:
Option 1 (returns Lamborghini and ends function):
showModelName: function() {
return(this.name);
console.log(this.name);
}
Option 2 (returns Lamborghini 2 times):
showModelName: function() {
console.log(this.name);
return(this.name);
}
Upvotes: 1
Reputation: 64657
Not sure exactly what you are trying to do, but it seems like there are two issues, first because you return
before you log it, and because you still need to use this.showModelName
, not just showModelName
return(this.name); // nothing after this line will run
console.log(showModelName);
var sportsCar = {
name: "Lamborghini",
color: "red",
horsepower: "100mph",
electric: true,
showModelName: function() {
console.log(this.showModelName);
return(this.name);
}
};
console.log(sportsCar.showModelName())
Upvotes: 3
Reputation: 1215
Your console.log needs to be above the return statement. Anything below the return statement will be ignored.
Also, the main reason why you aren't seeing the statement is because you defined a function. But it doesn't look like you've invoked it.
try running sportsCar.showModelName()
below the sportsCar object
Upvotes: 1
Reputation: 4562
This is the correct syntax
var sportsCar = {
name: "Lamborghini",
color: "red",
horsepower: "100mph",
electric: true,
showModelName: function() {
console.log(this.name);
}
};
sportsCar.showModelName();
Upvotes: 1