这是工作代码:
var test = function ()
{
console.log(test.data);
};
test.data = 'hello';
test.set = function (data)
{
test.data = data;
};
test.set('Test');
test();
这会将 Test
输出到我的 javascript 控制台。
现在我想知道,是否有办法使用类似的方法来做到这一点?
var test = {
this: function ()
{
console.log(test.data);
},
data: 'hello',
set: function (data)
{
test.data = data;
}
};
最佳答案
正如我在评论中所写,您不能使对象“可调用”。但是,您可以从第一个示例中自动执行该过程:
function extend(func, props) {
for(var prop in props) {
if(props.hasOwnProperty(prop)) {
func[prop] = props[prop];
}
}
return func;
}
然后调用它:
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()
调用每个方法,将会更容易理解。
至少你必须非常仔细地记录这一点。
关于Javascript 函数有子函数/变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4906675/