Pergunta

I have a simple OOP code I started:

(function(window,document){
    var _data = {
        get:function(d){ return _data.data[d] },
        set:function(prop,param){ _data.data[prop]=param },
        remove:function(d){ delete _data.data[d] },
        data:{}
     }; 
     window._data = _data.hasOwnProperty() ? _data.data : _data;
})(window);

What I want done when I type _data alone it'll return _data.data then if I do _data.get(... it'll do what each property needs to do. How is this done?

OR

(function(window,document){
    var _data = {
        get:function(d){ if(!d){return _data.data } else { return _data.data[d] } },
        set:function(prop,param){ _data.data[prop]=param },
        remove:function(d){ delete _data.data[d] },
        data:{}
     }; 
     window._data = _data;
})(window);
Foi útil?

Solução

It sounds like you're asking for _data to represent two different things depending upon whether a property was used with it or not. You can't do that in javascript.

You can do this in the global scope:

var _data = {
    get:function(d){ return _data.data[d] },
    set:function(prop,param){ _data.data[prop]=param },
    remove:function(d){ delete _data.data[d] },
    data:{}
 }; 

Then, _data.get() will call that method and return data.

But, when you just refer to _data, you're going to get the whole _data object above, not just _data.data.


The only thing remotely like what you're asking for I can think of would be to make _data be a function like this:

function _data() {
    return _data.data;
}

_data.get = function(d){ return _data.data[d] };
_data.set = function(prop,param){ _data.data[prop]=param };
_data.remove = function(d){ delete _data.data[d] };
_data.data = {};

This works because a function is an object that can have properties.

Then, you could do:

_data()

And that would give you _data.data.

Or, you could do :

_data.get(x)

And that would call the get method.


If you offered some explanation for why you're trying to do this, we could probably offer other ideas.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top