简体   繁体   中英

Understanding the call method in D3

I'm having a hard time understanding how the call method is used in D3 and how that compares to its other uses in JavaScript.

My understanding of how the call method in standard JS is that it allows a function to be called within a particular context. For example:

let JoJo = {
    name: `JoJo`,
    age: 33
};

function sayName(){
  console.log(`My name is ${this.name}`);
}

sayName.call(JoJo);

This ensures that sayName() is called in the context of JoJo (ie as if it were a method of the JoJo object).

But that seems to be different than how it's used here by Scott Murray:

var xAxis = d3.svg.axis()
                  .scale(xScale)
                  .orient("bottom");
svg.append("g")
    .call(xAxis);

As Murray explains:

D3's call() function takes a selection as input and hands that selection off to any function...That g becomes the selection for the next link in the chain. call() hands that selection off to the xAxis function, so our axis is generated within the new g.

So in the first example, call is being used to evoke a function within the context of a particular object (which call takes as its argument). In the second, it's just passing an object along to a function (which call takes as its argument).

I'm fairly new to both JS and D3, but it seems to me like there are two pretty different things going on in these examples. Clearly I'm missing something fundamental here. If anyone could shed some light on this, I'd be very grateful!

Your first example is Function.prototype.call , which has nothing to do with D3 selection.call : different methods, same name.

As a curiosity, internally D3 selection.call uses Function.prototype.apply , which is quite similar to Function.prototype.call . By the way, D3 has other methods which have the same name of vanilla JavaScript methods, like selection.filter , that one can confuse with Array.prototype.filter .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM