Radex Radex - 9 days ago 6
Javascript Question

How to access a function wihtin another function when added as property?

I need to call function b from c. I am using the following code and I receive an error.
Could you tell me what is wrong here?



var a = function() {
this.b = function() {
alert('b');
};
};

var c = function() {
a.b();
};

c();




Answer

You could create an instance of a with new operator.

var a = function() {
    this.b = function() {
        alert('b');
    };
};

var c = new a;

c.b();

Another way is to add a property to the function and call it without a new instance.

var a = function() {};

a.b = function() {
    alert('b');
};

var c = function() {
    a.b();
};

c();