search
HomeWeb Front-endJS TutorialWhat are the common mistakes that newbies make when using JS?

This time I will bring you what are the frequent errors when using JS for newbies. What are the precautions and what are the common mistakes when using JS for newbies. The following is a practical case, let's take a look.

1. Foreword

During this period of time, there are many people interviewing and sharing interview questions. Some time ago, I also served as an interviewer temporarily. In order to roughly understand the level of the interviewers, I also wrote a question and interviewed several front-end developers. During this period of time, I was learning and writing about some knowledge about Design Patterns. Unexpected knowledge about design patterns is what frequently makes people fall into the trap in interview questions.

So, today I will summarize the test points that make people fall into traps. Not much to say below, let’s take a look at the detailed introduction.

2.Object-orientedProgramming

Regarding object-oriented and process-oriented, I personally feel that these two They are not absolutely independent, but mutually complementary. As for when to use object-oriented and when to use process-oriented, specific situations require detailed analysis.

For object-oriented programming. There is a highly praised answer on Zhihu:

Object-oriented: dog.eat(shit)

Process-oriented: eat.(dog,shit)

But this example feels like It's not very elegant. I changed it and gave a more elegant example to illustrate the difference between object-oriented and process-oriented.

Requirements: Definition of 'waiting to eat hot pot'

The object-oriented thinking is: waiting. Action (eating hot pot)

The process-oriented thinking is: action (waiting, eating Hot pot)

Code implementation:

//面向对象
//定义人(姓名)
let People=function(name){
 this.name=name;
}
//动作
People.prototype={
 eat:function(someThing){
 console.log(`${this.name}吃${someThing}`);
 }
}
//守候是个人,所以要创建一个人(new一次People)
let shouhou=new People('守候','男',24);
shouhou.eat('火锅');
//面向过程
let eat=function(who,someThing){
 console.log(`${who}吃${someThing}`);
}
eat('守候','火锅');

The results are the same, they all output 'Waiting to eat hot pot'. But what if I'm full now and ready to code. How to achieve this? Looking at the code

//面向对象
shouhou.coding=function(){
 console.log(this.name+'写代码');
}
shouhou.coding();
//面向过程
let coding=function(who){
 console.log(who+'写代码');
}
coding('守候');

the result is the same: 'Waiting to write code'

But it is not difficult to find that object-oriented is more flexible, reusable and scalable. Because object-oriented is to perform certain actions against objects (in the example: 'waiting'). These actions can be customized and extended.

And process-oriented defines many actions to specify who will perform this action.

Okay, that’s it for the simple explanation of object-oriented. As for the three major characteristics of object-oriented: inheritance, encapsulation, and polymorphism, you can search for information online by yourself.

3.this

When developing using JavaScript, many developers will be more or less pointed to by this It’s confusing, but in fact, regarding the direction of this, remember the core sentence: which object calls the function, and this in the function points to which object.

Let’s discuss several situations below

3-1. Ordinary function call

There is no special surprise in this case, it just points to the global object - window .

let username='守候'
function fn(){
 alert(this.username);//undefined
}
fn();

Maybe everyone is confused why it is not output waiting, but after a closer look, the way I declared it is let, not the window object

If it is output Wait, write like this

var username='守候'
function fn(){
 alert(this.username);//守候
}
fn();
//---------------
window.username='守候'
function fn(){
 alert(this.username);//守候
}
fn();

3-2. Object function call

I believe this is not difficult to understand, it is the function call, where this points to

window.b=2222
let obj={
 a:111,
 fn:function(){
 alert(this.a);//111
 alert(this.b);//undefined
 }
}
obj.fn();

Obviously, the first time is to output obj.a, which is 111. The second time, obj does not have the attribute b, so the output is undefined, because this points to obj.

But you have to pay attention to the following situation

let obj1={
 a:222
};
let obj2={
 a:111,
 fn:function(){
 alert(this.a);
 }
}
obj1.fn=obj2.fn;
obj1.fn();//222

I believe this is not difficult to understand. Although obj1.fn is assigned from obj2.fn, the function is called by obj1, so this points to obj1 .

3-3.ConstructorCalling

let TestClass=function(){
 this.name='111';
}
let subClass=new TestClass();
subClass.name='守候';
console.log(subClass.name);//守候
let subClass1=new TestClass();
console.log(subClass1.name)//111

This is not difficult to understand, just recall (the four steps of new) and it’s almost the same !

But there is a pitfall. Although it generally does not appear, it is necessary to mention it.

Returning an object in the constructor will return the object directly instead of the object created after executing the constructor

3-4.apply和call调用

apply和call简单来说就是会改变传入函数的this。

let obj1={
 a:222
};
let obj2={
 a:111,
 fn:function(){
  alert(this.a);
 }
}
obj2.fn.call(obj1);

此时虽然是 obj2 调用方法,但是使用 了call,动态的把 this 指向到 obj1。相当于这个 obj2.fn 这个执行环境是 obj1 。apply 和 call 详细内容在下面提及。

3-5.箭头函数调用

首先不得不说,ES6 提供了箭头函数,增加了我们的开发效率,但是在箭头函数里面,没有 this ,箭头函数里面的 this 是继承外面的环境。

一个例子

let obj={
 a:222,
 fn:function(){ 
  setTimeout(function(){console.log(this.a)})
 }
};
obj.fn();//undefined

不难发现,虽然 fn() 里面的 this 是指向 obj ,但是,传给 setTimeout 的是普通函数, this 指向是 window , window 下面没有 a ,所以这里输出 undefined 。

换成箭头函数

let obj={
 a:222,
 fn:function(){ 
  setTimeout(()=>{console.log(this.a)});
 }
};
obj.fn();//222

这次输出 222 是因为,传给 setTimeout 的是箭头函数,然后箭头函数里面没有 this ,所以要向上层作用域查找,在这个例子上, setTimeout 的上层作用域是 fn。而 fn 里面的 this 指向 obj ,所以 setTimeout 里面的箭头函数的 this ,指向 obj 。所以输出 222 。

4.call和apply

call 和 apply 的作用,完全一样,唯一的区别就是在参数上面。

call 接收的参数不固定,第一个参数是函数体内 this 的指向,第二个参数以下是依次传入的参数。

apply接收两个参数,第一个参数也是函数体内 this 的指向。第二个参数是一个集合对象(数组或者类数组)

let fn=function(a,b,c){
console.log(a,b,c);
}
let arr=[1,2,3];

如上面这个例子

let obj1={
 a:222
};
let obj2={
 a:111,
 fn:function(){
  alert(this.a);
 }
}
obj2.fn.call(obj1);

call 和 apply 两个主要用途就是

1.改变 this 的指向(把 this 从 obj2 指向到 obj1 )

2.方法借用( obj1 没有 fn ,只是借用 obj2 方法)

5.闭包

闭包这个可能大家是迷糊,但是必须要征服的概念!下面用一个例子简单说下

let add=(function(){
let now=0;
return {
 doAdd:function(){
 now++;
 console.log(now);
}
}
})()

然后执行几次!

上图结果看到,now 这个变量,并没有随着函数的执行完毕而被回收,而是继续保存在内存里面。

具体原因说下:刚开始进来,因为是自动执行函数,一开始进来会自动执行,这一块

然后把这个对象赋值给 add 。由于 add 里面有函数是依赖于 now 这个变量。所以 now 不会被销毁,回收。这就是闭包的用途之一(延续变量周期)。由于 now 在外面访问不到,这就是闭包的另一个用途(创建局部变量,保护局部变量不会被访问和修改)。

可能有人会有疑问,闭包会造成内存泄漏。但是大家想下,上面的例子,如果不用闭包,就要用全局变量。把变量放在闭包里面和放在全局变量里面,影响是一致的。使用闭包又可以减少全局变量,所以上面的例子闭包更好!

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue+axios如何实现请求拦截功能

vue2实现购物车与地址选配案例分析

The above is the detailed content of What are the common mistakes that newbies make when using JS?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function