Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 985
Arūnas Smaliukas Avatar asked Jan 11 '15 10:01

Arūnas Smaliukas


1 Answers

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).

like image 182
Quentin Avatar answered Oct 07 '22 01:10

Quentin