【发布时间】:2014-02-20 14:50:36
【问题描述】:
我经常通读源代码作为学习编程的好资源。我正在查看 Backbone.Model 的 fetch() 方法并有这个问题,我希望有人能解释一下。
这里是 fetch() 方法:
// ---------------------------------------------------------------------
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overriden,
// triggering a `"change"` event.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var success = options.success;
options.success = function(model, resp, options) {
if (!model.set(model.parse(resp, options), options)) return false;
if (success) success(model, resp, options);
};
return this.sync('read', this, options);
}
我的问题是,if 条件 if (options.parse === void 0)... 的意义何在? void 0 简单地评估为“未定义”,那么这是测试属性是否未定义的简写吗?如果是这样,它是否比标准的 (typeof options.parse === 'undefined') 语句有任何优势,我发现它更具语义和可读性?
【问题讨论】:
-
见stackoverflow.com/q/4806286/989121。可能
typeof对他们来说太冗长了。 -
酷,谢谢。所以听起来它是
undefined的一种稍微严格的形式,因为undefined本身可以在大多数旧版本的Javascript 中被覆盖。 -
即使 undefined 被覆盖,未定义变量的 typeof 仍然会返回 'undefined',还是我遗漏了什么?
-
@kinakuta:据我了解,如果您分配
undefined = 'foobar',那么它的类型实际上将变为“字符串”。然后,如果您测试尚未定义的变量的类型,它将评估为“字符串”。但是,我无法检查这一点,因为运行旧版本的 ECMAScript 真的很难,它仍然允许覆盖undefined的值 :) javascriptweblog.wordpress.com/2010/08/16/… -
你可以在 IE8 兼容模式下运行 IE 来测试一下。如果您为 undefined 分配另一个值,则在测试未定义变量的类型时仍然会得到“未定义”。