最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Object context - Stack Overflow

programmeradmin0浏览0评论

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 the parent or self in-order to access the methods, so it would be: console.log(this.name); more information can be found over at MDN. – faino Commented Aug 4, 2013 at 17:50
Add a ment  | 

3 Answers 3

Reset to default 3

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).

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"
发布评论

评论列表(0)

  1. 暂无评论