Reviewing the past and learning the new can make you happy
First of all, please remember this V8 online manual - http://izs.me/v8-docs/main.html.
Do you still remember the building.gyp file from last time?
{
"targets": [
{
"target_name": "addon",
"sources": [ "addon.cc" ]
}
]
}
Just like this, if you have a few more *.cc files, it will look like this:
"sources": [ "addon.cc", "myexample.cc" ]
Last time we separated the two steps. In fact, configuration and compilation can be put together:
$ node-gyp configure build
Have you finished reviewing? without? !
Okay, let’s continue.
Table of Contents
Function parameters
Now we finally have to talk about parameters.
Let us imagine that there is such a function add(a, b) which represents adding a and b and returning the result, so first write the function outline:
#include
using namespace v8;
Handle
{
HandleScope scope;
//... Here we go again!
}
Arguments
This is the parameter of the function. Let’s take a look at v8’s official manual reference first.
•int Length() const
•Local
We don’t care about the rest, these two are important! One represents the number of parameters passed into the function, and the other bracket is used to access the nth parameter through the subscript index.
Therefore, we can roughly understand the above requirements as args.Length() is 2, args[0] represents a and args[1] represents b. And we need to determine that the type of these two numbers must be Number.
Notice that the index operator in square brackets returns a Local
•IsArray()
•IsBoolean()
•IsDate()
•IsFunction()
•IsInt32()
•IsNativeError()
•IsNull()
•IsNumber()
•IsRegExp()
•IsString()
•...
I won’t list them one by one, you can read the documentation for the rest. 。:.゚ヽ(*´∀`)ノ゚.:。
ThrowException
This is a function we will use later. Details can be found in the v8 documentation.
As the name suggests, it throws an error. After executing this statement, it is equivalent to executing a throw() statement in the Node.js local file. For example:
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
It is equivalent to executing a Node.js:
throw new TypeError("Wrong number of arguments");
Undefined()
This function is also in the documentation.
Specifically, it is a null value, because some functions do not need to return any specific value, or there is no return value. At this time, Undefined() needs to be used instead.
Let’s do it, Saonian!
After understanding the above points, I believe you will be able to write the logic of a b soon. I will copy the code from the Node.js official manual and give it to you to go through:
#include
using namespace v8;
Handle
{
HandleScope scope;
// means that more than 2 parameters can be passed in, but in fact we only use the first two
If(args.Length()
{
// throw error
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
// Return null value
return scope.Close(Undefined());
}
If(!args[0]->IsNumber() || !args[1]->IsNumber())
{
// Throw an error and return null value
ThrowException(Exception::TypeError(String::New("Wrong arguments")));
return scope.Close(Undefined());
}
//
http://izs.me/v8-docs/classv8_1_1Value.html#a6eac2b07dced58f1761bbfd53bf0e366)
// `NumberValue` function
Local
}
Finally, write the export function at the end and it’s OK.
Callback function
In the last chapter, we only talked about Hello world. In this chapter, grandma made a conscious discovery and wrote another callback function.
As usual, we write the framework first:
using namespace v8;
Handle
{
HandleScope scope;
return scope.Close(Undefined());
}
func(function(msg) {
console.log(msg);
});
That is, it will pass in a parameter to the callback function. We imagine it is a string, and then we can console.log() it out.
First you need to have a string series
Without further ado, let’s feed it a string first and then talk about it. (√ ζ ε:)
But we have to make this string a universal type, because Node.js code is weakly typed.
Local
What? You ask me what is Local
Then let me talk about it a little bit, refer to it here and the V8 reference document.
As shown in the documentation, Local
Then let’s talk about Local.
There are two types of Handle, Local Handle and Persistent Handle. The types are Local
Then you need to have a parameter table series
How to get the command line parameters after calling C/C from the terminal command line?
#include
void main(int argc, char* argv[])
{
// ...
}
By the way, argc here is the number of command line parameters, and argv[] is each parameter. Then calling the callback function of Node.js, v8 also adopts a similar method:
~~QAQ is stuck in Handle
After I verified it in many aspects (SegmentFault, StackOverflow and a KouKou group), I finally solved the meaning of the three parameters of the above function.
I won’t say much about the next two parameters. One is the number of parameters, and the other is an array of parameters. As for the first parameter Handle
It is the same as apply in JS. In JS, you do
var context = ...;
cb.apply(context, [ ...args...]);
The object passed as the first argument becomes this within the function scope. More documentation on MDN. If you don't know JS well, you can read more about JS's this here: http://unschooled.org /2012/03/understanding-javascript-this/
——Excerpted from StackOverflow
In short, its function is to specify the this pointer of the called function. The usage of this Call is similar to bind(), call(), and apply() in JavaScript.
So what we have to do is to build the parameter table first, and then pass in the Call function for execution.
The first step is to display the conversion function, because it is originally an Object type:
Local
The second step is to create a parameter table (array):
Local
Last call function series
Call cb and pass the parameters in:
cb->Call(Context::GetCurrent()->Global(), 1, argv);
The first parameter here, Context::GetCurrent()->Global(), means getting the global context as this of the function; the second parameter is the number in the parameter table (after all, although Node.js The array has a length attribute, but the system actually does not know the length of the array in C, and you have to pass in a number yourself to indicate the length of the array); the last parameter is the parameter table we just created.
Final Chapter Final Document Series
I believe everyone is already familiar with this step, which is to write the function, then put it into the exported function, and finally declare it.
I will just release the code directly, or you can go directly to the Node.js documentation.
#include
using namespace v8;
Handle
{
HandleScope scope;
Local
const unsigned argc = 1;
Local
cb->Call(Context::GetCurrent()->Global(), argc, argv);
return scope.Close(Undefined());
}
void Init(Handle
NODE_MODULE(addon, Init)
Well done! Just do the last remaining steps yourself. As for calling this function in JS, I have mentioned it before.
Extra
Well, I feel like my study notes are becoming more and more unrestrained. Please break it down~
Let’s stop here today. In the process of writing study notes, I got into trouble again, such as the meaning of the parameters of the Call function.
If you think this series of study notes is still helpful to you, come and join me in the fun~Σ>―(〃°ω°〃)♡→

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.