norbidrak norbidrak - 1 month ago 9
Javascript Question

Accessing properties in nested function returning another function

Is there a way to access properties in nested functions like that :

function func(){

this.new_func=function(){
console.log("something");
return 'something';
}

this.someValue=7;

return function(){
return "something_diff";
};
}

var obj=new func();

obj(); //works with returning "something diff"
obj.new_func(); // TypeError: obj.new_func is not a function
obj.someValue; // undefined


I need to delete whole "return function()..." part in order to access "someValue" and "new_func()". Why is it acting like that, and is there a way to somehow access that properties, while still returning another function ??

Answer

When you have a constructor that returns an object, that object replaces whatever you assigned to this. So indeed, the members new_func and someValue are lost.

To combine the returned function together with the other members, you can do this:

function func() {
    var f = function() {
        return "something_diff";
    };
    f.new_func = function() {
        console.log("something"); 
        return 'something';
    }
    f.someValue = 7;
    return f;
}

var obj = new func();

console.log(obj());
obj.new_func();
console.log('someValue:', obj.someValue);