What are the differences between c and javascript?
The differences are: 1. C language is compiled into machine language, while JS is interpreted and executed as a script by the interpreter; 2. C language requires programmers to manually manage memory, while JS memory is processed by the interpreter. To manage; 3. C language implements multi-threading by calling system API, while JS is single-threaded.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1. C language is mainly compiled into machine language, while JavaScript is mainly interpreted and executed as a script by the interpreter;
2. C language requires programmers to manually manage memory (mainly refers to the heap Memory application and release), while JavaScript memory is managed by the interpreter;
3. JavaScript is a dynamically typed language, and the data type of variables can still change during runtime;
4. Functions in JavaScript form closures with variables that are accessible when they are defined;
5. Support for object-oriented features such as "class inheritance and polymorphism", and JavaScript can use prototype chains and Closures, etc. implement object-oriented inheritance, polymorphism and encapsulation. JavaScript that implements ECMAScript 2015 and above supports the definition of classes at the grammatical level;
6. C language can realize multiple functions by calling the system API. Threads can improve the CPU utilization during blocking operations (mainly IO) through multi-threading, while JavaScript is mainly single-threaded. The possible blocking operations of JavaScript are completed by the asynchronous API provided by the JavaScript runtime
For students with a C foundation, learning js is quite simple, and the syntax is similar. Here we mainly list the similarities and differences between the two. Basically, if you remember these similarities and differences, you can start using js. In just a few days or even a day of study, you can use js to call Baidu maps, draw three-dimensional models and other fun functions in QT.
In the QT development process, qss, qml, and js are often used, which are very similar to the front-end three-piece set (CSS/HTML/JS). Here is a record of the common syntax of JS.
The concept of function pointers in C language is also applicable in JS. However, the function pointers in JS are not at the compilation level, but at the interpretation level. The underlying implementation is different, but The usage is the same.
0. [Variable declaration] Variables in C language must be declared first and then used; while JS allows direct use without declaration. Of course, it also supports declaring first and then using, and using first and then declaring.
1. [Assignment and reference assignment] When assigning values to variables in js, except for the basic type which is copy assignment, "others" are all assignment references (the so-called "others" are actually object variables in JS ). Assignment in C language is copy assignment, unless you explicitly specify to assign a reference.
2. [Callback] Both have the concept of callback function, and the function name is the callback variable name. This is true for both C and JS.
3. [Self-calling]. JS can call it immediately when defining a function. The syntax is:
无参函数示例 (function fooA (){ //这里是函数体 })(); 有参函数示例: (function fooB(var a){ //这里是函数体 })(5);
is to define the entire function, enclose it in parentheses A (this is equivalent to getting the function pointer of the function), and then add a parentheses B (this is equivalent to executing this function), the following parentheses B can be used to fill in parameters. And the function name here can be omitted.
4. [Defining functions within functions] JS allows functions to be defined inside functions.
5. [Closure]
This concept is relatively new and I have never seen it in C/C. By reading the JS tutorial, I found that this thing is very simple, but the name is too bluffing. Wow, to put it simply, this programming technique allows a function to have local static variables.
Generally speaking, the scope of variables in JS is consistent with C. Variables within a function cannot be accessed outside the function unless you use the formal parameters or return value of the function to replace the local variables. The pointer is moved outside, so that the code outside the function can operate the local static variables inside a certain function through the pointer. Similarly, this technique also exists in JS, and its name is closure. The difference is that C throws a pointer to a local static variable from the function, while JS throws a pointer to a function that can operate this local variable.
For comparison, here is a C language version of "closure":
uint8_t *getBuf(void) { static uint8_t buf[1024]; return buf; } void sendCmd() { uint8_t *cmdBuf = getBuf(void); cmdBuf[0] = 0xA5; cmdBuf[1] = 0xFF; .... send(cmdBuf, 10); }
There is a local static array buf in the getBuf function, which cannot be accessed by other codes in the original program. But we use the return value of the function to send out its first address, thereby realizing access to the array by external code. For example, the sendCmd function uses this array.
The following is the JS version:
Scenario (1): Variable a and function B are defined in function A. Obviously B can access a. How can we let the code outside A access it? What about a? There are two ideas, one is to return a reference to a, and the other is a closure. I won’t talk about returning a reference, because the memory of a will be released after A is executed, and the reference of returning a cannot access a.
var aRef = (function A(){ var a = 2; return function B(){ return a++; } })(); alert(aRef()); alert(aRef());
The effect of the above code is to pop up a prompt box with the number 2 as the content, and then pop up the prompt box again with the number 3 as the content. Both function name A and function name B do not need to be written.
我们来分析一下上述代码,首先函数A是个自调用函数(也可以不自调用,后面有例子),所以A里面变量a立即被赋值为2,函数A的返回值为函数B的函数指针,所以变量aRef就是个函数指针,以后调用aRef( ),就相当于调用了函数B( )。而B( )的返回值为a++。按照JS的设计机制,这种情形下的变量a将会常驻内存,这就是实现了让函数A拥有局部静态变量,而这个局部静态变量,只能被A返回的函数指针(也即函数B)修改。
基于上述分析,我们可以把上述代码改成这样,更容易阅读:
var aRef = (function A(){ var a = 2; function B(){ return a++; } return B; })(); 也可以改成这样: function A(){ var a = 2; function B(){ return a++; } return B; } var aRef = A();//A没有进行自调用,只能在这里调一次,才能获取到B的函数指针
情形2:经典的JS定时器闭包。题目:使用for循环,每秒打印出for当前的值。
错误写法:
for(var i = 1; i <= 5; i++) { setTimeout(function(){ alert(i); }, 1000); }
执行的效果是,连续弹出5次数字5,而不是预想的依次弹出12345。原因是,第一次执行定时器的回调函数前,i的值就已经变成5了,后续4次定时回调,i的值也是5.
正确写法:
for(var i = 1; i <= 5; i++) { (function(a){ setTimeout(function(){alert(a);}, 1000); })(i); }
这里使用了一个匿名的自调用函数(为了叙述方便,我下面称之为out函数),在函数内部又声明了匿名的定时器回调函数(为了叙述方便,我下面称之为in函数),因此使得in函数成了闭包函数,从而使得out函数的局部变量a常驻内存了。
为了更清楚de看明白它的原理,我们再把这段代码改成这样,增强可读性:
function outFunc(a){ function inFunc(){ alert(a); } setTimeout(inFunc, 1000); } for(i = 0; i < 4; i++) { outFunc(i); }
这段代码看起来清晰了,可以一目了然地看出其中的闭包语法。
总结一下闭包就是:一旦执行了闭包函数所在的外部函数,那么这个外部函数所维护的局部变量,将会常驻内存。
最后来一个实例应用,看看闭包在实际场景中是如何应用的。题目:有如下C语言函数,请把它改成js版。
uint32_t readVol(void) { static uint8_t callCnt = 0; callCnt++; return callCnt; }
这个C函数的功能很简单,就是每次调用时,会返回该函数被调的次数,也即readVol这个函数拥有自己的局部静态变量。用js实现如下:
var readVol = (function () { var callCnt = 0; return function() { callCnt++; return callCnt; } })();
这个readVol函数与C语言的readVol函数功能完全一致。
【推荐学习:javascript高级教程】
The above is the detailed content of What are the differences between c and javascript?. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

Algorithms are the set of instructions to solve problems, and their execution speed and memory usage vary. In programming, many algorithms are based on data search and sorting. This article will introduce several data retrieval and sorting algorithms. Linear search assumes that there is an array [20,500,10,5,100,1,50] and needs to find the number 50. The linear search algorithm checks each element in the array one by one until the target value is found or the complete array is traversed. The algorithm flowchart is as follows: The pseudo-code for linear search is as follows: Check each element: If the target value is found: Return true Return false C language implementation: #include#includeintmain(void){i

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

How to output a countdown in C? Answer: Use loop statements. Steps: 1. Define the variable n and store the countdown number to output; 2. Use the while loop to continuously print n until n is less than 1; 3. In the loop body, print out the value of n; 4. At the end of the loop, subtract n by 1 to output the next smaller reciprocal.

C language functions include definitions, calls and declarations. Function definition specifies function name, parameters and return type, function body implements functions; function calls execute functions and provide parameters; function declarations inform the compiler of function type. Value pass is used for parameter pass, pay attention to the return type, maintain a consistent code style, and handle errors in functions. Mastering this knowledge can help write elegant, robust C code.

C language functions are reusable code blocks, receive parameters for processing, and return results. It is similar to the Swiss Army Knife, powerful and requires careful use. Functions include elements such as defining formats, parameters, return values, and function bodies. Advanced usage includes function pointers, recursive functions, and callback functions. Common errors are type mismatch and forgetting to declare prototypes. Debugging skills include printing variables and using a debugger. Performance optimization uses inline functions. Function design should follow the principle of single responsibility. Proficiency in C language functions can significantly improve programming efficiency and code quality.
