Reputation: 13
Why is it that when I run employee.report() on this object method I get alerts for "Undefined is John Smith", etc.
var employee = {
name: "John Smith",
job: "Programmer",
age: 31,
report: function() {
for (k in employee) {
alert(this.k + " is " + employee[k])
}
}
}
but when I run the loop the console like this
for (k in employee) {
alert(this.k + " is " + employee[k])
}
it returns the proper alerts ("name is John Smith", etc.)
Upvotes: 1
Views: 53
Reputation: 3117
@Barmar explain very well, I just add more detail
In your object method report
this
in this.k
points to employee
object
and you get Undefined
because employee
does not have a property named k
.
You should use this[k]
instead.
And in te loop outside of object
for (k in employee){
alert(this.k+ " is " +employee[k])
}
this
in this.k
points to global Window
object
Your code actually is
for (var k in employee){
alert(this.k+ " is " +employee[k])
}
k
will become a global variable. this.k
is same as window.k
or k
BTW: You should use const/let and use strict
for more clarify your variable
Upvotes: 0
Reputation: 2383
To access k
you should use k
instead of this.k
. so replace alert(this.k+ " is " +employee[k])
with alert(k+ " is " +employee[k])
then your code will work successfully.
References for understand this in js.
Upvotes: 1
Reputation: 780974
In the report
function this
is the employee
object, which doesn't have a k
property. So this.k
is undefined
. If you want to print the property name, just use k
:
alert(k + " is " + employee[k]);
Outside the function, this
is the global window
object. Global variables are automatically made properties of window
, so this.k
is the same as k
.
Upvotes: 0
Reputation: 374
Since you haven't defined employee
in the scope of the employee
variable, you must use the keyword this
to reference the object itself.
var employee = {
name: "John Smith",
job: "Programmer",
age: 31,
report: function(){
for (k in this){
alert(k+ " is " +this[k])
}
}
}
Upvotes: 0