Javascript函数具有子函数/变量 [英] Javascript function have sub functions / variables
问题描述
这是工作代码:
var test = function ()
{
console.log(test.data);
};
test.data = 'hello';
test.set = function (data)
{
test.data = data;
};
test.set('Test');
test();
这会将Test
输出到我的JavaScript控制台.
现在我在想,是否有办法使用这样的东西?
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)
{
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`
}
});
也就是说,我认为您不应该使用类似的功能.如果您只有一个普通"对象并使用obj.method()
而不是使用obj()
来调用每个方法,将会更容易理解.
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.
这篇关于Javascript函数具有子函数/变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!