Was Douglas Crockford wrong in strict mode?

I'm sure he was not. 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 like that?

 function in_strict_mode() { return !this; } 

If is_strict_mode() will be my method , then I will agree, because this then will point to the method containing the object, for example

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

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

+7
javascript strict
source share
3 answers
 function in_strict_mode() { return !this; } 

This function may return different results depending on what you call it. Remember that this context is defined by a function call, not a function definition. Therefore:

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

The Crockford version defines and calls the inner function immediately, so it can control the this context inside the inner function call. Therefore, its in_strict_mode cannot be fooled to return something else using .call with a different this context.

+2
source share

The value of this depends on how the function is called. ("Anonymous" in Crockford's code, but only "only" in yours) determines whether strict mode is enabled if you look at the value of this and require that the function be called without an explicit context for work.

It doesn't matter what you call the Crockford function in_strict_mode , because it uses another function to actually get the data it cares about.

It doesn't matter what you call your in_strict_mode function, because it uses itself to retrieve data.

The Crockford version is designed to get the right result, even if you use it as a method for an object or call it with apply(something) or call(something) .

+7
source share

The feature shown will work in both directions ... i.e. you can put it in the "namespace" and still say whether you are in strict mode or not.

A simplified version of return !this will not return the correct result if it is placed in a namespace and called using mylib.in_strict_mode() .

+2
source share

All Articles