Why doesn't using a call function match the correct argument?

Function.prototypehas both call, and applywhich can be used to apply the function. Today I was going to use it applyfor something, but managed to sneak into a typo:

function foo(a) { console.log('foo', a) }

foo.call.apply(null, [1])

It took me a while to understand what I was able (presumably under the influence of something) to write .callbefore .apply. However, I was surprised that this would cause TypeError:

> function foo(a) { console.log(a) }
undefined
> foo.call.apply(null, [1])
TypeError: object is not a function
    at repl:1:10

It overwhelmed me a bit until I realized what it should be because the function is callbound to null. So I thought, let's try binding it to fooand see what happens:

> foo.call.apply(foo, [1])
foo undefined

, , . , a - undefined. . .call :

> foo.apply(foo, [1])
foo 1

, : call apply:

> foo.apply.call(foo, 1)
foo undefined

, . - - - , , , , , .

call apply ?

+4
2
foo.call.apply(null, [1])

Function.prototype.call null 1 .

, : Function.prototype.call(1); (this), null. call null, " ".

foo.call.apply(foo, [1])

- , call. Function.prototype.call(1); (this), foo. : foo.call(1).

call apply, :

foo.call.apply(foo, [null, 1]);

.call, .

+3

foo:

function log() {
  console.log('args: ', arguments, '\nthis: ', this);
}

call bind. log.call , apply, . , :

log.apply.call === log.call
log.call === Function.prototype.call


:

log.call.apply(null, [1])

- , :

Function.prototype.call.apply(null, [1])

Function.prototype.call window, 1 .

, , ; call , , , , , 1.

+1

Source: https://habr.com/ru/post/1532884/


All Articles