【发布时间】:2011-08-02 15:42:10
【问题描述】:
每当我为网站编写大型 JavaScript 库时,我都会使用以下模式。
虽然在运行时一切看起来都很好,但在 Visual Studio 中总是会做噩梦。
在匿名函数表达式的最后一行我总是得到错误
“预期;”
在最后的右括号上
}(窗口,jQuery));
我通过 jslint 运行代码没有任何问题,但我的智能感知总是中断,我无法格式化代码。我错过了什么吗?
; (function (window, $) {
// Define a local copy of MyLibrary
var MyLibrary = {},
// Shortcuts.
// A central reference to the root messages object
$$messages,
// A central reference to the root messages.messageType object
$$messageType;
MyLibrary = function () {
// The MyLibrary object is actually just the init
// constructor 'enhanced'
return new MyLibrary.fn.init();
};
MyLibrary.fn = MyLibrary.prototype = {
init: function () {
// Initialise the object shortcuts.
$$messages = MyLibrary.fn.messages;
$$messageType = MyLibrary.fn.messages.messageType;
}
};
// Give the init function the MyLibrary prototype for later instantiation
MyLibrary.fn.init.prototype = MyLibrary.fn;
MyLibrary.fn.messages = {
/// <summary>
/// Provides means to provide feedback message to the client.
/// </summary>
messageType: {
information: "information",
error: "error",
success: "success"
}
};
MyLibrary.fn.tester = function () {
alert($$messageType.success);
};
// Expose MyLibrary to the global object
window.MyLibrary = window.$m = MyLibrary();
} (window, jQuery));
jQuery(document).ready(function () {
$m.tester();
});
【问题讨论】:
-
您看到声明开头的
;了吗? -
(function (window, $) { ... } (window, jQuery));我觉得应该是(function (window, $) { ... }) (window, jQuery); -
@Raynos:你说得对,它是最初的“;”它可以保护自己免受任何其他不以一个结尾的脚本的关闭。将其粘贴在答案中,我会将您标记为正确答案。 Shame VS 不够聪明,无法确定这一点。 @Cem:语法可以以任何一种形式使用,但是我的语法是 crockford 推荐的语法,因为它更清楚地展示了表达式的范围。不过还是谢谢。
-
'mark down' 对你来说可能意味着一件好事?
-
@Sehe:呵呵呵呵...英语的精妙之处嗯?
标签: javascript jquery visual-studio-2010