Javascript函数有子函数/变量
这是工作代码:
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;
}
};
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)
{
test.data = data;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如我在评论中所写,您不能使对象“可调用”。但是,您可以从第一个示例开始自动化该过程:
然后使用以下命令调用它:
DEMO
也就是说,我认为你不应该使用这样的函数。如果您只有一个“普通”对象并使用 obj.method() 调用每个方法而不是 obj() ,那么会更容易理解。
至少你必须非常仔细地记录这一点。
As I have written in my comment, you cannot make an object "callable". You can however automate the process from your first example:
and then call it with:
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 havingobj()
.At least you have to document this very carefully.
这样做怎么样:
这样做的好处是可以轻松创建新实例。
如果你只是想要一次性的,我会说你自己的建议几乎就是你想要的:
但也许你的问题是如何避免“.log”部分?
How about doing something like this:
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:
But perhaps your question was how to avoid the ".log" part?
您可以将任何函数存储在对象的属性下。你可以调用它们:
将会完美地工作。我不确定您是否可以使用“this”作为属性名称,因为它是关键字。这可能没有问题,但可能会产生误导。
You can store any functions under properties in your object. And you can invoke them:
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.