0

my problem seems to be that my object function is not visible if i call it from within an object of functions. Example Code:

function foo()
{
   this.bar = function() 
              { 
                 alert("hit me!"); 
              }

   this.sna = { 
                 fu:   function () 
                       {
                          this.bar();
                       }
              };

}

this seems to refer to sna instead of foo. How do i adress foo? this.parent does not work.

2
  • I suggest you do some research about understanding this and scoping in javascript - it's a too wide topic to be explained in a short answer on SO Commented Aug 10, 2015 at 15:31
  • See stackoverflow.com/questions/16502467/…. You cannot access bar using this when you called your method by ….sna.fu.bar(), as it does reference …sna.fu. Commented Aug 10, 2015 at 16:05

2 Answers 2

1

Use a variable to refer to this(Foo). See this - JavaScript | MDN

function Foo() {
    this.bar = function() {
        console.log("hit me!");
    };

    var that = this;

    this.sna = {
        fu: function() {
            that.bar();
        }
    };

}

var foo = new Foo();
foo.bar();
foo.sna.fu();

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

Comments

1

One option is to add a reference to this:

function foo() {

  var _t = this;

  this.bar = function() { };

  this.child = {
    this.foo = function() {
      _t.bar():
    };
  };

}

Comments

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.