Rag*_*nis 7 javascript function object
这是工作代码:
var test = function ()
{
console.log(test.data);
};
test.data = 'hello';
test.set = function (data)
{
test.data = data;
};
test.set('Test');
test();
Run Code Online (Sandbox Code Playgroud)
这输出Test到我的JavaScript控制台.现在我想知道,如果有办法使用这样的东西吗?
var test = {
this: function ()
{
console.log(test.data);
},
data: 'hello',
set: function (data)
{
test.data = data;
}
};
Run Code Online (Sandbox Code Playgroud)
正如我在评论中所写,你不能使一个对象"可以调用".但是,您可以从第一个示例自动执行该过程:
function extend(func, props) {
for(var prop in props) {
if(props.hasOwnProperty(prop)) {
func[prop] = props[prop];
}
}
return func;
}
Run Code Online (Sandbox Code Playgroud)
然后用以下方法调用它:
var test = extend(function(){
console.log(test.data);
},
{
data: 'hello',
set: function (data) {
this.data = data; // note that I changed it to `this.data`
}
});
Run Code Online (Sandbox Code Playgroud)
也就是说,我认为你不应该使用这样的功能.如果你只是拥有一个"普通"对象并使用obj.method()而不是调用每个方法,那么将更容易理解obj().
至少你必须非常仔细地记录下来.