Assume I have a simple object in js with one private variable:
function test(){
var value=true;
}
and now I want to create one instance:
var r=new test() //I want to get r === true
How can I return a value from it?
If I write:
function test(){
var value=true;
return value;
}
I have a test {} in result.
If I write:
function test(){
var value=true;
return function(){ return value; }
}
then I can get the value, but I must add additional parentheses:
var r=new test()() //r === true
I don’t want the parentheses, so I tried to change the code to:
function test(){
var value=true;
return (function(){ return value; } )();
}
But in response, again I get test {}
How to write the return statement in this situation?
First I feel obliged to clarify a possible misunderstanding:
is not an object with a private variable. It is a function with a local variable. When you call the function with
new, it creates an object inheriting from the functions’s prototype with no properties. If you call the function normally, it simply executes the function body and returnsundefined(since you are not returning anything).Solutions:
Do you actually need a constructor function? I’m asking because your example is very simple. Obviously you cannot have the function return two values,
trueand the object.So, you could just call the function without
new:If you really want
rto betruethen I see no reason to call the function as a constructor function.The reason why you got
test {}as result was because you called the function withnew. If you do that, the function will always return an object and if you don’t do so explicitly (valueis a boolean, not an object), it implicitly returnsthis(which is an object).So again, if you really want
rto be equal tovaluefrom inside the function, then simply don’t call the function withnew.If you need an object though, there are a couple of ways:
You can assign the value to a property and access it instead, like PokeHerOne showed in his answer or add a function which returns that value, as papaiatis demonstrates. The advantage is that the value is accessed explicitly and other people looking at your code understand what’s going on.
Additionally, depending on what you want to do with that value / object, you can implement the
valueOfmethods, which gets called by various operators.For example:
I.e.
tis an object but behaves like the valuetrue(value) in various operations. This is powerful but can also be quite confusing, since the type conversion is somewhat implicit and it’s not something that is used in JavaScript very often.