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 plete explanation .Thank u @all.
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 plete explanation .Thank u @all.
Share Improve this question edited Aug 4, 2013 at 17:52 Maizere Pathak.Nepal asked Aug 4, 2013 at 17:46 Maizere Pathak.NepalMaizere Pathak.Nepal 2,4114 gold badges30 silver badges41 bronze badges 1-
When you're within the
Object
you have to reference theparent
orself
in-order to access themethods
, so it would be:console.log(this.name);
more information can be found over at MDN. – faino Commented Aug 4, 2013 at 17:50
3 Answers
Reset to default 3You'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).
An object member is referenced through the current object using this
:
height: function() { console.log( this.name ); }
// ^^^^
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"