search
HomeWeb Front-endJS TutorialJavaScript encapsulation that you must learn every day_javascript skills

こんにちは、JavaScript の基本についてはすでに説明しました。ここでは、OOP (オブジェクト指向プログラミング) について少しずつ説明していきます。 OOP を言語として使用するプログラマーは、OOP が何なのかさえ知らない、または OOP について聞いたことがあるだけで理解できておらず、オブジェクト指向のコードを書くことができない場合、プログラミングを学ぶ必要はありません。 , オブジェクト指向とは何か、プロセス指向とは何かについて詳しく紹介します。オブジェクト指向を理解するには、まずプロセス指向について知る必要があります。プロセスの方向性を理解した後は、OOP のためにやみくもに OOP を実行することはできません。それは、ほとんどの場合、小さな問題を解決するためだけにコードを作成するためです。 OOP を記述する必要はなく、プロセス指向のコードを記述するだけで済みます。「ローカルの状況に対策を適応する」という言葉を使用してください。

まずはプロセス指向から始めましょう。まず、私たちが通常「プログラム」と呼ぶものは、実際にはプロセスを実行することを意味します。プロセスとは、9時に定刻に会社に到着し、結果がどうであれ、完了すべきいくつかのことを行い、午後6時に出勤プロセスが完了し、会社を出る、これがこれです。プロセス; より具体的な例を挙げてみましょう。引き出しでは、実行プロセスをより明確に記述します。

1. キャッシュカードを ATM に持って行きます

2. 銀行カードを挿入します

3. パスワードを入力します

4. 出金金額を入力します

5. ATM がお金を吐き出す

6. お金をポケットに入れてください

6. 希望の番号がない場合は、ステップ 4 に戻ります

7. 領収書を印刷する場合は、「領収書を印刷」をクリックします。印刷したくない場合は、この手順をスキップします。

8. 返却カード

9. 手続き完了

上記のステップから、最初のステップから最後のステップまでが実行シーケンスであり、ステップ 4 から 6 が循環プロセス、ステップ 7 が分岐プロセス、つまり、プログラム。コードを記述する目的は、いくつかの動作プロセスをシミュレートし、コンピューターの高速コンピューティング特性を利用して私たちの生活に役立てることです。

引き出しを関数にカプセル化し、必要に応じてこの関数を呼び出して作業の必要を完了することができます。以下では、最も単純なプログラム プロセスを表現するために最も単純な例を使用します。 >


看图说话,在合适的时候,我们调用KissWife函数,输入合适参数,我们执行完一个过程了。

  OOP的目的就是提高代码的重用率,用最少的代码干尽量多的事,使用参数,也是面向对象编程的一种体现,我们来举个反例,如果我们在不使用参数的情况下,我们在想亲别人老婆的时候,就要重新写一个KissWife函数,这样,我们就写了大量重复的代码,不方便代码管理,诸多不便,方法不顺溜,就算在亲别人老婆的时候被发现的机率就大大增加了,带来了一些不必要的麻烦。

这时候有同学想问了,我觉得,我觉得我不习惯使用参数,就是不想传递参数,代码管理哪里会出现不方便管理呢?好,这个问题问得相当的到位。

我来解释一下吧,如果在这个过程执行过程中,我们发现有不合理的地方,需要修改,例如,我还想伸个舌头啥的,我们就要在亲自己老婆的函数中修改(麻烦),还要在亲别人老婆的函数中修改(麻烦+1),当我们有很多个类似的函数的时候,是不是要全部做修改(麻烦+n);第二个坏处就是修改次数多了,你能保证一次性全部修改都不会出错吗(容易失误),这就能体现出了,如果我们只是完全写一些重复性的代码,工作效率大打折扣。

  通过上面的讲解,其实新手读者们还是没能理解什么是OOP(面向对象编程),我们现在就从对象(object)开始讲解,这里的对象,不能单纯地理解成谈恋爱时所处的男女朋友,对象是指世间的万事万物,太阳,大海,人,宠物……;每一种我们可以想得到的事物,每一个对象都有自己的属性,行为。

我们就可以像上图这样来理解,鸟就是一个对象,它有自己属性,有自己的行为,下面我们就用具体代码来封装一个关于鸟的类。(注:在javascript语言中function关键字中仅仅用来定义函数,也可以定义类,它不能像高级语言那样使用Class关键字,后面我们讲继承的时候,我们还会用特殊方法来实现继承)

//声明一个鸟类
function Bird(){
 this.name = "鸽子";
 this.color = "灰色";
 this.habitat = "笼子";
 this.weight = "500克";
}

//使用原型链的方式,来定义鸟的行,也可以用来定义属性,但是,属性一般用this关键字来声明
//行为和属性,其实同一个级别的,后面我们用for in来给大家验证

//鸣叫
Bird.prototype.Sing = function(){
 console.log("咕咕咕");
}
//进食
Bird.prototype.Eat = function(){
 console.log("吃了一粒玉米");
}
//飞翔
Bird.prototype.Fly = function(){
 console.log("在天空中飞翔着");
}
//孵蛋
Bird.prototype.Brood = function(){
 cossole.log("正在孵化鸽子蛋");
}

现在我们类已经声明好了,但是我们,怎么使用它呢?现在它只是一个类,还不是实例,就是我口头上所说的鸽子,实例,就是一只具体的鸽子,怎么才能得到一只具体的鸽子呢?看下面的代码

//用new 关键字来获得一个实例
var gezi = new Bird();

现在我们就可以调用它的属性,以及方法了

通过这样的方法我们所得到的每一个鸽子其实都是一样的,我们要怎么才得到有自己特征的鸽子呢?有自己独有特征,其实就是属性不一样,那们我们就来改造一下函数的声明

//其实我们只需要在这里小小地修改一下
function Bird(_color,_habitat,_weight){
 this.name = "鸽子";
 this.color = _color;
 this.habitat = _habitat;
 this.weight = _weight;
}

然后我们来看一下实例化一个鸽子的时候,怎么做

//我们现在就实例化了两个鸽子
var gezi_A = new Bird("白色","野外","300克");
var gezi_B = new Bird("灰白色","温室","550克");

这样,我们就可以构造出有自己特征的鸽子出来了,从上面的例子,我们其实已经不难看出,封装,其实就是把我们可以形容的对象用类来表示,我们就可通过new关键字来实例化出对象,这个对象就有自己独立的属性,行为,这样的一个对象,我们就可以方便的供我们操作,封装就是一种体现OOP的方法,我们先是封装一个类,然后,再new 出实例,这样写就比我们直接用代码来构造两次鸽子类少了很多的代码,如果我们还构造第3只鸽子,就再new 一次就可以了,构造对象的时候,就感觉一句代码的事。提高代码的重用率,OOP就这样体现出来了。

  这时候,有人问了,只是在说我们用OOP的好处 ,还没有看到不用OOP的代码到底怎么写,那们就来一个不用OOP的方式,同样以鸽子为例

//声明一个鸽子
function GeZi_C(){
 console.log("种类是鸽子");
 console.log("颜色是蓝色");
 console.log("住在树梢上");
 console.log("体重400克");
 console.log("在天空中飞翔着");
}
//执行一次
GeZi_C();

如果我们要再声明100个鸽子,是不是要写大量重复类似上面这样的代码呀,这就是面向过程的代码。相信新手朋友们已经有一个模糊的OOP概念了吧,慢慢体会,这种感觉不一两天就能弄明白的,一口吃不成大胖子,后面我们还会继续讲OOP思想的继承和多态。

继续先前在声明Bird类的时候,说的属性和行为是同一级别,而且是可以用两种方式来声明,属性在构造函数里面用 this 关键字声明,行为函数用 prototype 关键字来声明,prototype就是函数原型链的标准扩展,我们之所以这样来写,就是把javascript语言的使用代入高级语言的范畴,用来模拟高级语言的使用,扯远了,我们先来验证一下Bird实例对象中是不是拥有在同一级别的属性跟行为函数

//我们现在是用的前面的没有参数的Bird类
var obj = new Bird();

//逐一打印出来
for(var pro in obj){
  console.log(pro + " : " + obj[pro]);
}

看到了吧,for...in就作用就是用来循环遍历对象的属性以及数组的下标,行为函数的名称其实也是对象的属性,现在就验证了前面的说法,相信大家现在对OOP的封装思想有一定的认知了。

总结一下,今天我们所讲的东西其实就是把事物给抽象的拟态一下,然后,把这些属性行为给封装成一个类,使用new关键字实例化出具体对象,这样大大地提高了代码的使用率,提高了工作效率。

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor