2

How to access somevar:'this is Foo' from inside bar.foo() ?

function Foo(){
    this.somevar='this is Foo';
}
Foo.prototype={
    bar:{
        somevar:'this is bar'
        ,foo:function(){
            console.log(this);
        }
    }
}

var instance = new Foo();
instance.bar.foo();

Here is link to jsfiddle: http://jsfiddle.net/jct8n/3/

4
  • You can just access Foo.prototype.somevar - or do I misunderstand the question? Commented Jan 1, 2012 at 13:22
  • @Lucero - That approach should work except that if someone does var foo = new Foo(); and then foo.somevar = 'newValue', calling foo() would still print 'this is Foo' instead of 'newValue'. Commented Jan 1, 2012 at 13:25
  • 1
    @Beck You want the members of prototype objects to be methods. Adding objects which itself contain methods doesn't sound like a good pattern. Commented Jan 1, 2012 at 14:00
  • Yea, guess that's my mistake. I'll have to create separate class instead of nested object. Thanks ;) Commented Jan 1, 2012 at 14:03

3 Answers 3

3

I think perhaps the scoping rules of the language will not allow this in any straightforward way. The best suggestion I can come up with to get what you want (short of renaming somevar to get rid of the clash in the first place) is to use apply() to change the value of this inside of foo(), like:

var instance = new Foo();
instance.bar.foo.apply(instance);

Here's a fiddle:

http://jsfiddle.net/jct8n/2/

Sign up to request clarification or add additional context in comments.

2 Comments

Well yea, passing as parameter is an option. But it's madness to pass it on each method inside nested object. And what if both contexts are required? :S
@Beck The this value provides you with one context. If you want another one, you'll need to pass it in as an argument...
2

I use this method for public and private instance variables:

http://robertnyman.com/2008/10/14/javascript-how-to-get-private-privileged-public-and-static-members-properties-and-methods/

Comments

1
console.log(Foo.prototype.somevar);

Alternatively, you should consider just renaming one of the somevar variables to easily allow for what you're looking to do, as well as eliminating some complexity and confusion.

2 Comments

And how to access property from current instance only?
I'd strongly recommend just using the 2nd part of this answer - rename one of the somvar variables to eliminate the clash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.