0
var namespace = {
    test: function() {
         //sample 1
         function nest(param) {
            console.log('a '+ param);
         }
         //sample 2
         this.nest = function(param) {
            console.log('b '+ param);
         }
    }
}

Can anyone explain how to call and access the nested function? Thanks in advance!

1 Answer 1

1

You are defining the nest function within the scope of test and it will only be accessible within test. The this.nest function is defined according to the context of your test function which is the namespace variable. This makes that version of nest accessible outside the test function even though you define it within the function body.

Alter your code to this and you will see the different console output;

var namespace = {
    test: function() {
         //sample 1
         function nest(param) {
            console.log('a '+ param);
         }

         nest('sample 1');

         //sample 2
         this.nest = function(param) {
            console.log('b '+ param);
         }

         this.nest('sample 2');
    }
}
namespace.test();
namespace.nest('sample 3');

This will produce the following output;

a sample 1
b sample 2
b sample 3

Some suggested reading on scope and context; Understanding Scope and Context in JavaScript

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

2 Comments

Thanks you @Dave Anderson for your answered. However, namespace.nest('sample 3'); doesn't work bro
@JebooScr how are you testing this? I've put that code directly in Chrome console as well as a JSFiddle and the console outputs all the log calls from places.

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.