一种功能和一种封装形式?
如果以前有人问过这个问题,我很抱歉,但我什至不确定使用什么搜索词来找到答案,当我尝试搜索时,我从来没有得到任何特定于这个问题的信息。
我正在使用 Javascript,我想知道是否可以做这样的事情:
find(x); // find a document (for example)
find.inFolder(y); // find a folder's documents (for example)
换句话说,我可以有一个也可以用作对象/类的函数吗?我知道我可以运行 find() 一次并返回一个哈希值,以便 find.inFolder() 可以工作,但我希望有一种方法可以让我继续调用 find()。
可以用原型来完成吗? (我的“原型”知识非常有限)
function find() {}
find.prototype.inFolder = function() {}
它可以在哈希内部完成吗? [我知道这段代码不起作用]
var find = {
() : function() {},
inFolder : function() {}
}
为了进一步推动它,有没有办法将 .inFolder() 的结果以这种方式发送到 find() 函数:
find().inFolder();
我知道你可能会说我不这样做了解 javascript 的概念,你基本上是正确的,但我看到人们用 JS 做了一些非常令人惊奇的事情,所以我想我应该问问那里的专业人士。
预先感谢您的任何帮助。
I'm sorry if this question has been asked before, but I'm not even sure what search terms to use to find the answer and when I try to search I never get anything specific to this question.
I'm using Javascript and I am wondering if it is possible to do something like this:
find(x); // find a document (for example)
find.inFolder(y); // find a folder's documents (for example)
In other words, can I have a function that can also be used as an object/class? I know I could run find() once and return a hash so that find.inFolder() would work, but I'm hoping there's a way where I could continue to call find().
Can it be done with prototype? (my "prototype" knowledge is very limited)
function find() {}
find.prototype.inFolder = function() {}
Can it be done inside a hash? [I know this code doesn't work]
var find = {
() : function() {},
inFolder : function() {}
}
To push it even further, is there a way to have the results of .inFolder() be sent to the find() function this way:
find().inFolder();
I know you might say that I don't understand the concept of javascript, and you'd be mostly correct, but I've seen people do some pretty amazing stuff with JS so I thought I'd ask the pros out there.
Thanks in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你所描述的是一个流畅的界面(如果你想要一些东西来搜索)。您可以完成类似您想要实现的目标,如下所示:
这是一个很棒的模式,尤其是在像 jQuery 这样的项目中使用时:
每个调用都会返回一个带有
.find()
,的 jQuery 对象>.first()
和许多其他函数,让您可以编写直观且流畅的代码。我有点喜欢你的
find().inFolder()
示例,所以这里有一个扩展版本:http://jsfiddle.net/andrewwhitaker/TCdTd/
What you're describing is a Fluent interface (if you want something to search for). You could accomplish something like what you're trying to achieve like this:
This is a great pattern, especially when leveraged in projects like jQuery:
Each call returns a jQuery object with
.find()
,.first()
and many other functions, which lets you write intuitive and fluid code.I kind of liked your
find().inFolder()
example, so here's an expanded version:http://jsfiddle.net/andrewwhitaker/TCdTd/
您可以将一个函数分配给另一个函数的成员:
jsFiddle。
但我不确定我是否理解这个问题。
You can assign, a function to a member of another function:
jsFiddle.
I'm not sure I understand the question however.