简体   繁体   中英

Was Douglas Crockford wrong with Strict Mode Example?

I'm sure he wasn't. I just don't understand one example from his presentation

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

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

Isn't it the same like this one?

function in_strict_mode() {
    return !this;
}

If is_strict_mode() would me method then I agree because this then would point to object containing method, for example

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

But why he did it in his example (which is simple function, not a method of an object)?

The value of this depends on how a function is called. The ("anonymous" in Crockford's code but "only" in yours) function determines if strict mode is on by looking at the value of this and requires that the function be called without explicit context for that to work.

It doesn't matter how you call Crockford's in_strict_mode function because it uses a different function to actually get the data it cares about.

It does matter how you call your in_strict_mode function, because it uses itself to get the data.

The Crockford version is designed to give the correct result even if you use it as a method on an object or call it using apply(something) or call(something) .

The function shown will work both ways... ie you can put it in a "namespace" and still will tell you if you're in strict mode or not.

The simplified version return !this won't return the correct result if placed in a namespace and invoked with mylib.in_strict_mode() .

function in_strict_mode() {
    return !this;
}

This function can return different results depending on how you call it . Remember that the this context is determined by the function call , not the function definition . Therefore:

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

Crockford's version defines and immediately calls an inner function, so it can control the this context inside the call to the inner function. Therefore, his in_strict_mode cannot be tricked to return something else by .call ing it with a different this context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM