If I get this right, you want an object to behave as, well, an object except for when it is passed to a function? the variable seven in your example is an object, so there's no way it'll simply return 7 when referenced anywhere.
What's more, num is essentially a private variable. So using for...in and JSON.stringify trickery won't do you any good. What you should do is either make the num variable an object property (this.num) or create a member function (this.getNum(){return num};).
After that, you can use the property/method freely:
alert(seven.num);//alerts 7, but requires num to be declared as a property
alert(seven.getNum());//alerts 7, requires the method
I'd suggest using a method in this case, since you're obviously using this function both as a constructor and a regular function (Which, might I add, isn't a very good idea).
On a slightly pedantic note: it is custom to capitalize the first letter of a constructor, and not to use names that might collide with JS native types (String, Number, Object, Function...)
function MyNumber(n)
{
this.num = n;//as a property
this.add = function(x)
{
return this.num + x;
}
}
var seven = new MyNumber(7);
alert(seven.num);//alerts 7
Though, if num shouldn't be altered -I'm guessing that's the case here- an extra function is the route I'd take:
function MyNumber(n)
{
var num = n;
this.add = function(x)
{
return num + x;
};
this.getNum = function()
{
return num;
};
}
alert(seven.getNum());
If you're still planning on using the constructor as a regular function, you're best of checking how the function/constructor was called:
function MyNumber(n)
{
var num = n;
if (!(this instanceof MyNumber))
{//not called as constructor
return num;//or a function, or something else (treat this as a closure)
}
//Same code as above goes here
}
I might be going a bit off topic here, but I can't help but think that you might want to read up on closures, objects and constructors in JavaScript.
.add?seven === 7is false.