我认为这是一个初学JavaScript问题。下面是一段代码(从Discover Meteor拍摄)来说明:什么时候在JavaScript中需要function()块?
Meteor.methods({
// why function is necessary here?
post: function(postAttributes) {
var user = Meteor.user(),
// why is not necessary here?
postWithSameLink = Posts.findOne({
url: postAttributes.url
});
// ensure the user is logged in
if (!user)
throw new Meteor.Error(401, "You need to login to post new stories");
// ensure the post has a title
if (!postAttributes.title)
throw new Meteor.Error(422, 'Please fill in a headline');
// check that there are no previous posts with the same link
if (postAttributes.url && postWithSameLink) {
throw new Meteor.Error(302,
'This link has already been posted', postWithSameLink._id);
}
// pick out the whitelisted keys
// and why not below here?
var post = _.extend(_.pick(postAttributes, 'url', 'title', 'message'), {
userId: user._id,
author: user.username,
submitted: new Date().getTime()
});
var postId = Posts.insert(post);
return postId;
}
});
我相信这是一个简单的解释这一点。我如何解决这个困惑?
检查[如何匿名函数JavaScript工作](http://stackoverflow.com/questions/1140089/how-does-an-anonymous-function-in-javascript-work),[闭包](https://developer.mozilla.org/en -US/docs/Web/JavaScript/Guide/Closures)和[函数和函数范围](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions_and_function_scope)。 –