Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have to follow <code>charge</code> more carefully. It is variable defined in <a href="https://github.com/mbostock/d3/blob/v2.9.2/src/layout/force.js#L11" rel="nofollow">line 11</a>:</p> <pre><code>charge = -30, </code></pre> <p>The function <code>force.charge</code> which you quoted is for <strong>setting</strong> the charge, it is <strong>not</strong> the function referred to in <code>+charge.call(this, nodes[i], i);</code>. Have a look at the second line of <code>force.charge</code>:</p> <pre><code>charge = typeof x === "function" ? x : +x; </code></pre> <p><code>x</code> can be a function (callback) <em>you</em> pass, to dynamically calculate the charge. The current node (<code>nodes[i]</code>) and the index of the node (<code>i</code>) will be passed to this callback, so that you can calculate the charge dynamically based on these values:</p> <pre><code>force.charge(function(node, index) { return index * 2; }); </code></pre> <p><code>x</code> (and therefore <code>charge</code>) can also be a number or numerical string. That's why it is tested beforehand whether <code>charge</code> is a function or not:</p> <pre><code>if (typeof charge === "function") { // function so we call it and pass the current node and index } else { // static value, the same for each node } </code></pre> <hr> <p>Apert from that, you can always pass any number of arguments to a function, no matter how many parameters it has defined. For example:</p> <pre><code>function foo() { alert([].join.call(null, arguments)); } foo('a', 'b'); </code></pre> <p>will alert <code>a,b</code>.</p> <hr> <p>To answer your questions: The arguments passed to <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call" rel="nofollow"><code>.call()</code> <em><sup>[MDN]</sup></em></a> or <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply" rel="nofollow"><code>.apply()</code> <em><sup>[MDN]</sup></em></a> are passed in the same order to the function. So if I have a function <code>function foo(a, b, c)</code> then <code>foo.call(null, x, y)</code> would pass <code>x</code> as <code>a</code> and <code>y</code> as <code>b</code> (<code>c</code> would be <code>undefined</code>).</p> <p>The <code>+</code> operator is the <a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Arithmetic_Operators#.2B_%28Unary_Plus%29" rel="nofollow"><em>unary plus</em> operator <em><sup>[MDN]</sup></em></a>, which simply converts the operand into a number.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload