Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is this possible or am I barking up the 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);

// 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());

Update:

The object which fnc is supposed to represent is actually a Sarissa dom document. Here is a more elaborate version of fnc(), dom_doc(). The accepted answer below has been integrated into the 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 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;
}

Demo: JSFIDDLE

like image 372
Serhiy Avatar asked May 09 '13 22:05

Serhiy


People also ask

How to create a function from string in JavaScript?

Use the eval () method to create a function from the string. It accepts the function in the form of string and converts it to JavaScript function. In this example, It takes 2 arguments and returning the sum of both numbers. Example 2: This example uses approach as discussed above. // Till this point we can use 'func' as function.

What is a JavaScript function?

A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when "something" invokes it (calls it). Example

How many ways a function can be created in JavaScript?

There are four ways a function can be created in JavaScript. They are as follows: A function as a statement A function as an expression

How to declare a function in JavaScript?

JavaScript also has a huge number of inbuilt functions. For example, Math.sqrt () is a function to calculate the square root of a number. In this tutorial, you will learn about user-defined functions. The syntax to declare a function is: A function is declared using the function keyword.


2 Answers

You seem to be talking about a getter method. If that's what you mean, you can use this:

var data = 'one';
function fnc(){
    Object.defineProperty(this, 'out', {
        get : function(){ return data; }
    });
}
var instance = new fnc();

alert(instance.out);

http://jsfiddle.net/zztYd/1

This is not compatible with older browsers (see the compatibility table at the bottom of this page).

Also, it's a little weird to use a getter to fetch a global variable. Usually you use that to get the value of a private variable on your instance object, and in that case you could only modify it with a corresponding setter.

like image 105
bfavaretto Avatar answered Oct 13 '22 01:10

bfavaretto


The alternative to bfavaretto's solution is to use the literal syntax for an object. Has almost the same level of support as Object.defineProperty().

Also, you should call Object.defineProperty only once, not with every instantiation.

I'm also going to provide a more realistic example, that is, the property gets calculated, instead of just referencing a global.

http://jsfiddle.net/mendesjuan/zztYd/3/

function Pair(a,b){
    this.a = a;
    this.b = b;
}

Pair.prototype = {
    get sum(){ 
        return this.a + this.b; 
    }
};

var pair = new Pair(1,2);
alert(pair.sum);
pair.a = 5;
alert(pair.sum);

The benefit of this is that you can change the implementation to be storage instead of calculation and you won't have to change how it's called.

function Pair(a,b){
    this.a = a;
    this.b = b;
    this.sum = a + b;
}

Pair.prototype = {
    setA: function(a){ 
        this.a  = a;
        this.sum = this.a + this.b; 
    }
};

var pair = new Pair(1,2);
alert(pair.sum);
pair.setA(5);
alert(pair.sum);

Notice that you do have to now call setA so that sum can be recalculated. Or you could use a setter.

function Pair(a,b){
    this.a = a;
    this.b = b;
    this.sum = a + b;
}

Pair.prototype = {
    set a(a) {
        this.a  = a;
        this.sum = this.a + this.b; 
    }
};

var pair = new Pair(1,2);
alert(pair.sum);
pair.a = 5;
alert(pair.sum);
like image 29
Juan Mendes Avatar answered Oct 13 '22 01:10

Juan Mendes