0

Lets say we have function test():

function test(){
    a();

    this.b = function(){
        alert(1);
    }

    function a(){
        this.b();
    }
}

var t = new test();

This code will throw TypeError: this.b is not a function

The question is, how can we correctly access b() from within a()?

1
  • As I understand now there were 2 problems: this in a() wasnt reffering to test() and invocation of nested function that is using object's properties must be after declaration of these properties. Commented Apr 19, 2014 at 19:48

2 Answers 2

2

Change the order:

function test(){
    var me = this;
    this.b = function(){
        alert(1);
    }

    a();

    function a(){
        me.b();
    }
}

You can't call this.b() before you've assigned the variable. And you need to use a local variable to capture the value of this in the closure.

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

Comments

0
function test(){
  var me = this;

  this.b = function () {
    console.log(1);
  }

  function a() {
    console.log('calling me.b()');
    me.b();
  }

  a();
}

var t = new test();
console.log('calling t.b()');
t.b();

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.