我希望有一种方法来指定某些 Javascript 方法需要哪些属性、它们应该匹配什么模式,以及如果不匹配如何响应。
这是因为它会导致大量重复代码来检查方法级别的必需和可选参数。
举这个例子。在这里我想建立一个灯箱。如果他们向我发送一个字符串,我将显示一个仅包含内容的灯箱。如果他们向我发送一个选项对象,我会查找“标题”和“内容”。能够以某种标准化的方式指定这一点不是很好吗?
// Static method for generating a lightbox
// callerOptions = '' //if sent a string, the lightbox displays it with no title
// callerOptions = {
// content: '' // required popup contents. can be HTML or text.
// , title: '' // required title for the lightbox
// , subtitle: '' // optional subtitle for lightbox
// }
lightbox = function (callerOptions) {
if (!callerOptions) {
log.warn(_myName + ': calling me without a message to display or any options won\'t do anything');
return;
}
// If they send us a string, assume it's the popup contents
if (typeof(callerOptions) === 'string') {
this.options = {};
this.options.content = callerOptions;
// Otherwise assume they sent us a good options object
} else {
this.options = callerOptions;
}
_build();
_contentLoaded();
};
我很想能够使用一些我从未听说过的库来做这样的事情:
// Maybe this is what it looks like with a method signature enforcement library
lightbox = function (callerOptions) {
TheEnforcer(
, { valid: [
'string' // assumes that it is testing type against arguments by convention
, 'typeof([0].title) === "string" && typeof([0].content) === "string"'
]
}
});
// If they send us a string, assume it's the popup contents
if (typeof(callerOptions) === 'string') {
this.options = { 'content': callerOptions };
// Otherwise we know they sent us a good options object
} else {
this.options = callerOptions;
}
_build();
_contentLoaded();
};
有人见过这样的 Javascript 库吗?也许内置到 1000 个 JS MV* 框架之一中?
编辑: 看起来这通常由 MV* 框架处理。 Backbone.js 的模型属性具有验证值和默认值。我认为这些可以用来满足或几乎满足我在这里介绍的用例。
最佳答案
(这本来是一条评论,但它比预期的要长。)
我知道这样的功能有时会很有用,但我相信应该尽可能避免它。我认为 ECMA 标准不应该包含这一点。
举个例子:灯箱标题和内容是必需的。为什么?为什么不显示一个没有标题或内容的空灯箱?在我看来,这是一个不错的后备方案。如果您正在构建 API,则无论使用它的人都可以检查空标题和内容,并且如果需要,则不调用灯箱函数。另外,我不喜欢尝试在 JS 中强制执行类型的想法。
我认为这与 jQuery 完全不同。它们只是提供了一个可链接的包装对象(里面有一堆有用的方法),并支持某种编码/语法风格,这就是 jQuery 的大部分内容。与强制执行类型和方法签名不同,它使语言看起来更简单 - 绝对不是“尽可能简单”(对此感到抱歉)。
关于javascript - 是否有用于强制方法签名的 Javascript 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10212859/