Douglas Crockford 的 Strict Mode Example 是不是错了?

Was Douglas Crockford wrong with Strict Mode Example?

我确定他不是。我只是不明白他的演讲中的一个例子

http://youtu.be/UTEqr0IlFKY?t=44m

function in_strict_mode() {
    return (function () {
        return !this;
    }());
}

这不也一样吗?

function in_strict_mode() {
    return !this;
}

如果is_strict_mode()会让我method那么我同意,因为this然后会指向包含方法的对象,例如

my_object.in_strict_mode = function() {
    return (function () {
        return !this;
    }());
}

但是为什么他在他的示例中这样做(这是简单的函数,而不是对象的方法)?

this 的值取决于函数的调用方式。 ("anonymous" 在 Crockford 的代码中,但 "only" 在你的代码中) 函数通过查看 this 的值来确定是否开启严格模式,并要求在没有明确上下文的情况下调用该函数工作。

您如何调用 Crockford 的 in_strict_mode 函数并不重要,因为它使用不同的函数来实际获取它关心的数据。

如何调用 in_strict_mode 函数很重要,因为它使用自身来获取数据。

Crockford 版本旨在提供正确的结果,即使您将其用作对象的方法或使用 apply(something)call(something).

调用它也是如此

显示的函数可以双向工作...即您可以将它放在 "namespace" 中,并且仍然会告诉您是否处于严格模式。

如果将简化版本 return !this 放置在命名空间中并使用 mylib.in_strict_mode() 调用,则不会 return 正确的结果。

function in_strict_mode() {
    return !this;
}

此函数可以return 不同的结果取决于您如何调用它。请记住,this 上下文是由函数 call 决定的,而不是由函数 definition 决定的。因此:

in_strict_mode.call(new Object()) === false

Crockford 的版本定义并立即调用一个内部函数,因此它可以控制内部函数调用内部的 this 上下文。因此,他的 in_strict_mode 不能通过 .call 使用不同的 this 上下文被欺骗到 return 其他东西。