Tuesday, 22 November 2016

Javascript: 'this' and call

In this post, my assertion that

impl.apply(impl, deps) = impl.apply(null, deps);

just shows how naive I was due to the lack of understanding of 'this' mechanism.

From You Don't Know JS: this & Object Prototypes

function foo(num) {
    console.log( "foo: " + num );

    // keep track of how many times `foo` is called
    // Note: `this` IS actually `foo` now, based on
    // how `foo` is called (see below)
    this.count++;
}

foo.count = 0;

var i;

for (i=0; i<10; i++) {
    if (i > 5) {
        // using `call(..)`, we ensure the `this`
        // points at the function object (`foo`) itself
        foo.call( foo, i );
    }
}
// foo: 6
// foo: 7
// foo: 8
// foo: 9

// how many times was `foo` called?
console.log( foo.count ); // 4 
The first parameter foo essentially makes 'this' point to the foo object.
Now replace the line with

foo.call( null, i );

It prints out '0' because this refers to window object now.

I am tempted to boldly make this assertion that the following two pairs of method invocation can always be used interchangeably.

foo.call( foo, i ) = foo.bind(foo)(i)
foo.call( null, i) = foo(i)  

Let's see when I can be proved wrong.


No comments:

Post a Comment