Wylliam Judd
Wylliam Judd

Reputation: 10895

Function.prototype.call and Function.prototype.apply with only one argument

What does Function.prototype.call or Function.prototype.apply do with only one argument?

What is going on here?

Function.prototype.myBind = function (context) {
  var fun = this;
  return function(){
    return fun.call(context);
  }
}

Upvotes: 1

Views: 96

Answers (2)

zzzzBov
zzzzBov

Reputation: 179046

fun.call(context)

the function in fun will be called with a context* of context and with no arguments passed.

This is essentially equivalent to calling:

context.temp = fun;
context.temp();

of course with call no additional properties would be added.

Here's an example:

var a = {foo: 'bar'},
    b = {foo: 'baz'};

function example() {
  console.log(this.foo);
}

console.log('example called on a');
example.call(a); //'bar'

console.log('example called on b');
example.call(b); //'baz'

* this inside the function

Upvotes: 2

SLaks
SLaks

Reputation: 887385

It calls the function without passing any arguments.

Upvotes: 4

Related Questions