Binding
- Node.js course
- Expert
- Lesson 9/47
- 5 min
Learn JS-to-C++ binding.
Binding
Binding is the act of connecting a JS function to native code. The native side calls the function, the JS side returns the result. A bindFunction(name, fn) function models this: it records the function's name and parameter count (arity).
fn.length gives the number of declared parameters of a JS function. Example: for function(a, b) { return a + b; }, .length is 2. bindFunction('add', add) returns {name: 'add', arity: 2}. During binding the native side uses this info: it calls by name and checks arity. This is the foundation of the bridge between native and JS. The output is add: 2; name and parameter count on one line.
What is arity?
Arity is the number of parameters a function expects. In JavaScript you get it with fn.length. Example: for function(a, b) {...}, .length is 2. For functions with default parameters .length counts only the non-default parameters.
Arity matters during binding: the native side does not call with the wrong count. bindFunction('add', add) records add's arity as 2; the native side reads it. console.log(bindFunction('add', add).name + ': ' + bindFunction('add', add).arity) prints add: 2. This is the most basic check of binding: name and parameter count. In real N-API actual parameters are fetched with napi_get_cb_info but arity is still useful.
Practice Write the binding function
Write function bindFunction(name, fn). Return {name: name, arity: fn.length}. Define const add = function(a, b) { return a + b; }. Print console.log(bindFunction('add', add).name + ': ' + bindFunction('add', add).arity).
Starter code
// Write a bindFunction
// Bind a JS function by name
// Return {name, arity} (arity is the parameter count)
// Print as 'add: 2'
// write hereSample solution
function bindFunction(name, fn) {
return {name: name, arity: fn.length};
}
const add = function(a, b) { return a + b; };
console.log(bindFunction('add', add).name + ': ' + bindFunction('add', add).arity);Expected output
add: 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each concept to its description
| Term | Meaning |
|---|---|
Binding |
Bridge between JS and native |
fn.length |
Parameter count |
arity |
Name for the parameter count |
name |
Function name |
2 What is function(a, b) { return a + b; }.length?
function(a, b) { return a + b; }.length- 2 Correct answer
- 3
- 0
- 1
Explanation: Two parameters (a, b) are declared, .length is 2.
3 Complete the arity value
return {name: name, arity: fn.____};
return {name: name, arity: fn.length};
Explanation: fn.length gives the parameter count.