Javascript: assign method and string to the same property name

I know that I am going to force people who say that I simply should not do this, but I am curious how people achieve this.

I know that I saw where you can enter the name of the property and get one value, but then you add the brackets to the end and the method is accessed.

Visually, I say this:

foo returns 'bar' foo() performs a function 

The question is how?

+6
source share
3 answers

No, but it seems ...

This can be done using valueOf

 var foo = function() { console.log("From Function"); return "Function"; }; foo.valueOf = function() { return "Variable"; }; alert( 'Output is: ' + foo() ) alert( 'Output is: ' + foo ) 

This cannot be done using JavaScript, because an element in an object can be two different objects.

If you want a property to be a function and an object, these are different

0
source

This is not possible because of how properties are solved on objects. This is the only thing that comes remotely:

 function f() { return 'I am being returned from the function.'; } f.toString = function () { return 'I am a property on the variable.'; } console.log('f() says: ' + f()); console.log('f says: ' + f); 

It relies on JS typecasts to function using the .toString method in certain scenarios.

+2
source

Note workaround using setTimeout

 var foo = (function() { var fn = function() { return foo && typeof foo === "string" ? function() { return "foobar" } : "bar"; }; setTimeout(function() { foo = fn() }); return fn() }()); console.log(foo); // `"bar"` setTimeout(function() { console.log(foo()); // `"foobar"` }); 
0
source

All Articles