Reputation: 2411
Do this Object have its context:
{}
if yes ,than it must also have VO(Variable Object) .So than,when i do this:
foo={
name:"Maizere",
height:function () {console.log(name);}//output is undefined
}
foo.height();
When the height() method gets run js first checks function context since it can't find that name ,it travels to next i.e parent context Vo and here parent context is the context of literal object ,since that name resides in that VO why i get undefined?
How is that property residing in the VO of the literal object context simply as a property or simply like variable ,i need a complete explanation .Thank u @all.
Upvotes: 1
Views: 3880
Reputation: 665020
You're confusing the call context (with the this
keyword) with the variable scope, and with object properties.
To answer your question: No, objects do not have a scope. Only functions have a scope attribute, which will initialise the scope chain of their variable object when they get called. Since there are no variables with the name name
in the scope of your height
function, it resolves to undefined
(or even a Reference Error).
Upvotes: 3
Reputation: 96845
An object member is referenced through the current object using this
:
height: function() { console.log( this.name ); }
// ^^^^
Upvotes: 2
Reputation: 66364
It looks like you want the this
keyword and you have a small SyntaxError on the name line (you wanted a ,
but wrote ;
).
var foo = {
name: "Maizere",
height: function () {
console.log(this.name);
}
};
foo.height(); // "Maizere"
Upvotes: 1