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.

Luca
  • 9,259
  • 5
  • 46
  • 59
Micha El
  • 73
  • 1
  • 8
  • 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 – Luca Aug 10 '15 at 15:31
  • See https://stackoverflow.com/questions/16502467/prototype-deep-scope-of-this-to-access-instances-scope. You cannot access `bar` using `this` when you called your method by `….sna.fu.bar()`, as it does reference `…sna.fu`. – Bergi Aug 10 '15 at 16:05

2 Answers2

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():
    };
  };

}
svidgen
  • 13,744
  • 4
  • 33
  • 58
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();
iplus26
  • 2,518
  • 15
  • 26