javascript - Is it possible to make a JavasScript function act as if it was a string, no () -


is possible or barking wrong tree here?

var data = 'one'; function fnc(){     this.out = function(){         return data;     } } var instance = new fnc();  alert(instance.out); data = 'two'; alert(instance.out);  // know achieve that, that's not know.  alert(instance.out()); data = 'two'; alert(instance.out()); 

update:

the object fnc supposed represent sarissa dom document. here more elaborate version of fnc(), dom_doc(). accepted answer below has been integrated function below.

function get_doc(dom_node) {     var doc;     if (navigator.useragent.indexof("msie") >= 0) {         doc = new activexobject("msxml2.domdocument.3.0");         doc.loadxml(document.getelementbyid(dom_node).text);     }     else {         doc = sarissa.getdomdocument();         doc = (new domparser()).parsefromstring(document.getelementbyid(dom_node).textcontent, "text/xml");         // runs xsltprocessor in modern browsers if trasformnode         doc.transformnode = function (stylesheet) {             var processor = new xsltprocessor();             processor.importstylesheet(stylesheet);             return new xmlserializer().serializetostring(processor.transformtodocument(this));         }          // allows modern browsers extract xml way legacy ies did         var getxml = {};         getxml.tostring = function(){             return new xmlserializer().serializetostring(doc);         };         doc.xml = getxml;     }     return doc; } 

demo: jsfiddle

jsfiddle demo

these types of workarounds bypass convention though. should not of hamper use () on functions. using () expected, readable, best practice, , industry standard.

not sure why smartcaveman decided remove answer of using tostring viable approach although hackish.

var data = 'one'; function fnc(){  var getdata = {};  getdata.tostring = function(){    return data;  };  this.out = getdata; }  var instance = new fnc();  alert(instance.out);//one data = 'two'; alert(instance.out);//two  var s = instance.out; alert(s);//two 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -