这是可能的吗,还是我在这里树上错误的树?
var data = 'one'; function fnc(){ this.out = function(){ return data; } } var instance = new fnc(); alert(instance.out); data = 'two'; alert(instance.out); // I know that this would achieve that,but that's not what I would like to know. alert(instance.out()); data = 'two'; alert(instance.out());
更新:
fnc应该表示的对象实际上是Sarissa dom文档.这是一个更精细的版本的fnc(),dom_doc().下面接受的答案已经被整合到下面的功能中.
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 as if it was trasformNode doc.transformNode = function (stylesheet) { var processor = new XSLTProcessor(); processor.importStylesheet(stylesheet); return new XMLSerializer().serializeToString(processor.transformToDocument(this)); } // allows modern browsers to extract xml the way the legacy IEs did var getXML = {}; getXML.toString = function(){ return new XMLSerializer().serializeToString(doc); }; doc.xml = getXML; } return doc; }
演示:JSFIDDLE
解决方法
jsFiddle Demo
这些类型的解决方法真的绕过了惯例.在函数上简单地使用()不应该是那么大的阻碍.使用()是预期的,可读的,最佳实践和行业标准.
不知道为什么smartcaveman
决定删除他使用toString的答案,但这是一个可行的方法,虽然有点黑客.
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