Javascript Function Has Sub Functions / Variables

This is the working code:

var test = function ()
{
    console.log(test.data);
};

test.data = 'hello';

test.set = function (data)
{
    test.data = data;
};

test.set('Test');
test();

This outputs Testto my javascript console. Now I was wondering if there was a way to do this using something like this?

var test = {
    this: function ()
    {
        console.log(test.data);
    },

    data: 'hello',

    set: function (data)
    {
        test.data = data;
    }
};
+5
source share
3 answers

As I wrote in my comment, you cannot make the object "callable". However, you can automate the process from the first example:

function extend(func, props) {
    for(var prop in props) {
        if(props.hasOwnProperty(prop)) {
            func[prop] = props[prop];
        }
    }
    return func;
}

and then call it with:

var test = extend(function(){
    console.log(test.data);
},
{
    data: 'hello',    
    set: function (data) {
        this.data = data;   // note that I changed it to `this.data`
    }
});

Demo


However, I think you should not use such functions. This will be easier to understand if you just have a “normal” object and call each method with obj.method()instead obj().

, .

+5

- :

function Test () {
  this.data = 'hello';
  this.set = function (data)
    {
        test.data = data;
    }
  this.log = function ()
    {
        console.log(test.data);
    }
}

var test = new Test ();
test.set('Test');
test.log();

, .


, , - , :

var test = {
    log: function ()
    {
        console.log(test.data);
    },

    data: 'hello',

    set: function (data)
    {
        test.data = data;
    }
};

test.set('Test');
test.log();

, , , ".log"?

+2

. :

let f = { fun1: function () 
                {
                     return 1; 
                } 
        };
f.fun1();

. , 'this' , . , , .

0

All Articles