Javascript function have 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 Test
to my javascript console.
Now I was wondering, if there was a way to do it using something like this?
var test = {
this: function ()
{
console.log(test.data);
},
data: 'hello',
set: function (data)
{
开发者_JAVA技巧 test.data = data;
}
};
As I have written in my comment, you cannot make an object "callable". You can however automate the process from your 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
That said, I think you should not use functions like that. It will be easier to understand if you just have a "normal" object and call every method with obj.method()
instead of having obj()
.
At least you have to document this very carefully.
How about doing something like this:
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();
This has the advantage you can create new instances easily.
If you just want a one-off, I would say your own suggestion is almost what you want:
var test = {
log: function ()
{
console.log(test.data);
},
data: 'hello',
set: function (data)
{
test.data = data;
}
};
test.set('Test');
test.log();
But perhaps your question was how to avoid the ".log" part?
You can store any functions under properties in your object. And you can invoke them:
let f = { fun1: function ()
{
return 1;
}
};
f.fun1();
is going to work perfectly. I am not sure if you can use 'this' as a property name as it is a keyword. Probably no problem with that, but it might be misleading.
精彩评论