I was testing a very simple code and I was expected to get error but I got a string "result" returned by console!
Here is the code:
var person = { name: "Mohammad", last_name: "Kermani"};
var show_person = function (age){
console.log(this.name +" is "+ age + " years old");
}
Now you now we can't use this.name
when JavaScript does not know what this
(object) is, then we need to use call
or apply
.
Now when I wrote this, I got "result" string (instead of error or warning):
show_person(20); //Returns: result is 20 years old
See Jsfiddle and what console returns.
The code with call
should be like:
show_person.call(person, 20); //Returns: Mohammad is 20 years old
What is the string "result" and why JavaScript does not return error when it does not have access to this.name
?
And what will happen if we don't use an object in a function and want to get one of its properties? (Like here, I wanted to get name of person object)