JS の OOP

Aug 29, 2024 pm 01:39 PM

OOP in JS

パラダイムは、コードのスタイル、その編成方法を指します。一般的なプログラミング パラダイムは、OOP、関数型などです。開発者になるには、OOP をよく理解する必要があります。

おっと

  • 最も人気のあるエンタープライズ プログラミング パラダイム。
  • オブジェクトに基づく
  • コードを整理することを目的として開発されました
  • コードをより柔軟にし、保守しやすくします。
  • OOP が導入される前は、コードは構造を持たずにグローバル スコープ内の複数の fn に分散していました。そのスタイルはスパゲッティ コードと呼ばれるもので、保守が非常に難しく、新しい機能を追加することは忘れてください。
  • コード経由でオブジェクトを作成するために使用されます。
  • また、オブジェクト間の相互作用も可能になります。

API

  • オブジェクトの外部のコードがアクセスして他のオブジェクトと通信するために使用できるメソッド。

クラス

  • オブジェクトを作成するための抽象的なブループリント。
  • クラスからインスタンス化されます。つまり、クラス ブループリントを使用して作成されます。
  • 「new Class()」構文を使用してクラスから複数のオブジェクトが作成されます

クラスのデザイン:

  • OOP の 4 つの原則、つまり抽象化、カプセル化、継承、ポリモーフィズムを使用して実行されます
  • 抽象化: エンドユーザーにとって重要ではない不要な詳細を非表示にします。
  • カプセル化: 一部のプロパティ メソッドをプライベートとして保持し、クラス内からのみアクセスできるようにし、クラス外からはアクセスできないようにします。外部世界と対話するためのパブリック インターフェイス API としていくつかのメソッドを公開します。したがって、内部状態[オブジェクトのデータ]がバグの大きな原因となる可能性があるため、外部コードによる内部状態の操作が防止されます。パブリックインターフェイスはプライベートではないコードです。メソッドをプライベートにすると、外部の依存関係を壊さずにコードの実装を変更することが容易になります。概要: 状態とメソッドを適切にカプセル化し、重要なメソッドのみを公開します。
  • 継承: 重複したコードは保守が困難です。したがって、この概念は、すでに記述されたコードを継承することによってコードの再利用性をサポートします。子クラスは、親クラスからすべてのプロパティとメソッドを継承することで親クラスを拡張します。また、子クラスは継承された機能とともに独自のデータ機能を実装します。
  • ポリモーフィズム: 子クラスは親クラスから継承されたメソッドを上書きできます。

オブジェクトは次のとおりです:

  • 現実世界または抽象的な特徴をモデル化するために使用されます。
  • にはデータ(プロパティ)とコード(メソッド)が含まれる場合があります。データとコードを 1 つのブロックに詰め込むのにご協力ください
  • 自己完結型のコード部分/ブロック。
  • appln の構成要素は相互に作用します。
  • 白黒オブジェクトの相互作用は、パブリック インターフェイス API を通じて行われます。
  • クラスから作成されたすべてのオブジェクトは、そのクラスのインスタンスと呼ばれます。
  • すべてのオブジェクトには異なるデータを含めることができますが、それらはすべて共通の機能を共有します

古典的な継承:

  • Java、C++、Python などでサポート
  • あるクラスが別のクラスを継承する
  • メソッドまたは動作はクラスからすべてのインスタンスにコピーされます。

JS での委任またはプロトタイプの継承:

  • 古典言語と同様に、すべての OOP 原則をサポートします。
  • クラスを継承するインスタンス。
  • プロトタイプには、そのプロトタイプにリンクされているすべてのオブジェクトにアクセスできるすべてのメソッドが含まれています。 プロトタイプ: メソッドが含まれています オブジェクト: proto リンクを使用してプロトタイプ オブジェクトに接続されたプロトタイプのメソッドにアクセスできます。
  • オブジェクトは、プロトタイプ オブジェクトで定義されたプロパティとメソッドを継承します。
  • オブジェクトは、プロトタイプ オブジェクトに動作を委譲します。
  • ユーザー定義の配列インスタンスは、Array.prototype.map() の .map()、つまり、proto リンクを介してプロトタイプ オブジェクトで定義された map() にアクセスします。したがって、.map() はインスタンスでは定義されず、プロトタイプで定義されます。
## 3 Ways to implement Prototypal Inheritance via:
1. Constructor Fn:
- To create objects via function.
- Only difference from normal fn is that they are called with 'new' operator.
- Convention: always start with a capital letter to denote constructor fn. Even builtins like Array, Map also follow this convention.
- An arrow function doesn't work as Fn constructor as an arrow fn doesn
t have its own 'this' keyword which we need with constructor functions.
- Produces an object. 
- Ex. this is how built-in objects like Array, Maps, Sets are implemented

2. ES6 Classes:
- Modern way, as compared to above method.
- Syntactic sugar, although under the hood work the same as above syntax.
- ES6 classes doesn't work like classical OOP classes.

3. Object.create()
- Way to link an object to its prototype
- Used rarely due to additional repetitive work.

ログイン後にコピー
## What does 'new' operator automates behind the scene?
1. Create an empty object {} and set 'this' to point to this object.
2. Create a __proto__ property linking the object to its parent's prototype object.
3. Implicit return is added, i.e automatically return 'this {} object' from the constructor fn.

- JS doesn't have classes like classical OOP, but it does create objects from constructor fn. Constructor fn have been used since inception to simulate class like behavior in JS.
Ex. validate if an object is instance of a constructor fn using "instanceOf" operator.

const Person = function(fName, bYear) {
  // Instance properties as they will be available on all instances created using this constructor fn.
  this.fName = fName;
  this.bYear = bYear;

  // BAD PRACTICE: NEVER CREATE A METHOD INSIDE A CONSTRUCTOR FN.
  this.calcAge = function(){
console.log(2024 - this.bYear);
}
};

const mike = new Person('Mike', 1950);
const mona = new Person('Mona', 1960);
const baba = "dog";

mike; // Person { fName: 'Mike', bYear: 1950 }
mona; // Person { fName: 'Mona', bYear: 1960 }

mike instanceof Person; // true
baba instanceof Person; // true


If there are 1000+ objects, each will carry its own copy of fn defn.
Its a bad practice to create a fn inside a contructor fn as it would impact performance of our code.
ログイン後にコピー

プロトタイプオブジェクト:

  • JS のコンストラクター fn を含む各関数には、プロトタイプ オブジェクトと呼ばれるプロパティがあります。
  • このコンストラクター fn から作成されたすべてのオブジェクトは、コンストラクター fn のプロトタイプ オブジェクトにアクセスできます。元。人物.プロトタイプ
  • 次の方法で fn をこのプロトタイプ オブジェクトに追加します。 Person.prototype.calcAge = function(byear){ console.log(2024 - b年); };

マイク.calcAge(1970); // 54
mona.calcAge(1940); // 84

  • mike オブジェクトには .calcAge() が含まれませんが、Person.prototype オブジェクトで定義された proto リンクを使用してそれにアクセスします。
  • 'this' は常に関数を呼び出すオブジェクトに設定されます。

マイク。プロト; // { calcAge: [関数 (匿名)] }
mona.プロト; // { calcAge: [関数 (匿名)] }

mike.プロト === 人物.プロトタイプ; // true

  • Person.prototype here serves as prototype for all the objects, not just this single object created using Person constructor fn.

Person.prototype.isPrototypeOf(mike); // true
Person.prototype.isPrototypeOf(Person); // false

  • prototype should have been better named as prototypeOfLinkedObjects generated using the Constructor fn.
  • Not just methods, we can create properties also on prototype object. Ex. Person.prototype.creatureType = "Human"; mike.creatureType; // Human mona.creatureType; // Human

Different properties for an object:

  • Own property and properties on constructor fn accessbile via proto link of objects.
  • To check own property for objects, use:
    mike.hasOwnProperty('fName'); // true
    mona.hasOwnProperty('creatureType'); // false

  • Two way linkage:
    Person() - constructor fn
    Person.prototype - Prototype

Person() constructor fn links to Person.prototype via .prototype
Person.prototype prototype links back to Person() constructor fn via .constructor to Person() itself.

proto : always points to Object's prototype for all objects in JS.
newly created object is automatically returned, unless we explicitly return something else and stored in the LHS variable declared.

Prototype Chain:

  • Similar to scope chain. Look for variable in the scope level
  • Prototype chain has to lookup for finding properties or methods.
  • All objects in JS has a proto link Person Person.proto Person.proto.proto; // [Object: null prototype] {}

Top Level Object in JS:
Object() - constructor fn
Object.prototype - Prototype
Object.prototype.proto // null

Object.prototype methods:

  • constructor: f Object()
  • hasOwnProperty
  • isPrototypeOf
  • propertyIsEnumerable
  • toLocaleString
  • toString
  • valueOf
  • defineGetter etc

// Takes to constructor fn prototype
mike.proto === Person.prototype; // true
// Takes to parent of constructor fn's prototype i.e Object fn
mike.proto.proto; // [Object: null prototype] {}
// Takes to parent of Object fn i.e end of prototype chain
mike.proto.proto.proto; // null

  • All fns in JS are objects, hence they also have a prototype
  • console.dir(x => x+1);
  • Fns are objects, and objects have prototypes. So a fn prototype has methods which can be called.
  • const arr = [2,4,21]; // is same as using 'new Array' syntax
    arr.proto; // shows fns on array's prototype

  • Each array doesn't have all of these methods, its able to use it via proto link.

  • arr.proto === Array.prototype; // true

const arr = [2,4,21];
arr.proto; // Array prototype
arr.proto.proto; // Object prototype
arr.proto.proto.proto; // null

## If we add a fn to Array.prototype, then all newly created arrays will inherit that method. However extending the prototype of a built-in object is not a good idea. Incase new version of JS adds a method with the same name, will break your code. Or in case multiple Devs create similar fnality with different names will add an unnecessary overhead.
Ex. Add a method named unique to get unique values
const arr = [4,2,4,1,2,7,4,7,3];
Array.prototype.uniq = function(){
return [...new Set(this)];
}
arr.uniq(); // [ 4, 2, 1, 7, 3 ]
ログイン後にコピー
  • All DOM elements behind the scene are objects.
  • console.dir(h1) // will show you it in object form
  • Prototype chain: h1 -> HTMLHeadingElement -> HTMLElement -> Element -> Node -> EventTarget -> Object

以上がJS の OOPの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

フロントエンドのサーマルペーパーレシートのために文字化けしたコード印刷に遭遇した場合はどうすればよいですか? フロントエンドのサーマルペーパーレシートのために文字化けしたコード印刷に遭遇した場合はどうすればよいですか? Apr 04, 2025 pm 02:42 PM

フロントエンドのサーマルペーパーチケット印刷のためのよくある質問とソリューションフロントエンド開発におけるチケット印刷は、一般的な要件です。しかし、多くの開発者が実装しています...

javascriptの分解:それが何をするのか、なぜそれが重要なのか javascriptの分解:それが何をするのか、なぜそれが重要なのか Apr 09, 2025 am 12:07 AM

JavaScriptは現代のWeb開発の基礎であり、その主な機能には、イベント駆動型のプログラミング、動的コンテンツ生成、非同期プログラミングが含まれます。 1)イベント駆動型プログラミングにより、Webページはユーザー操作に応じて動的に変更できます。 2)動的コンテンツ生成により、条件に応じてページコンテンツを調整できます。 3)非同期プログラミングにより、ユーザーインターフェイスがブロックされないようにします。 JavaScriptは、Webインタラクション、シングルページアプリケーション、サーバー側の開発で広く使用されており、ユーザーエクスペリエンスとクロスプラットフォーム開発の柔軟性を大幅に改善しています。

誰がより多くのPythonまたはJavaScriptを支払われますか? 誰がより多くのPythonまたはJavaScriptを支払われますか? Apr 04, 2025 am 12:09 AM

スキルや業界のニーズに応じて、PythonおよびJavaScript開発者には絶対的な給与はありません。 1. Pythonは、データサイエンスと機械学習でさらに支払われる場合があります。 2。JavaScriptは、フロントエンドとフルスタックの開発に大きな需要があり、その給与もかなりです。 3。影響要因には、経験、地理的位置、会社の規模、特定のスキルが含まれます。

Shiseidoの公式Webサイトのように、視差スクロールと要素のアニメーション効果を実現する方法は?
または:
Shiseidoの公式Webサイトのようにスクロールするページを伴うアニメーション効果をどのように実現できますか? Shiseidoの公式Webサイトのように、視差スクロールと要素のアニメーション効果を実現する方法は? または: Shiseidoの公式Webサイトのようにスクロールするページを伴うアニメーション効果をどのように実現できますか? Apr 04, 2025 pm 05:36 PM

この記事の視差スクロールと要素のアニメーション効果の実現に関する議論では、Shiseidoの公式ウェブサイト(https://www.shisido.co.co.jp/sb/wonderland/)と同様の達成方法について説明します。

JavaScriptの進化:現在の傾向と将来の見通し JavaScriptの進化:現在の傾向と将来の見通し Apr 10, 2025 am 09:33 AM

JavaScriptの最新トレンドには、TypeScriptの台頭、最新のフレームワークとライブラリの人気、WebAssemblyの適用が含まれます。将来の見通しは、より強力なタイプシステム、サーバー側のJavaScriptの開発、人工知能と機械学習の拡大、およびIoTおよびEDGEコンピューティングの可能性をカバーしています。

JavaScriptは学ぶのが難しいですか? JavaScriptは学ぶのが難しいですか? Apr 03, 2025 am 12:20 AM

JavaScriptを学ぶことは難しくありませんが、挑戦的です。 1)変数、データ型、関数などの基本概念を理解します。2)非同期プログラミングをマスターし、イベントループを通じて実装します。 3)DOM操作を使用し、非同期リクエストを処理することを約束します。 4)一般的な間違いを避け、デバッグテクニックを使用します。 5)パフォーマンスを最適化し、ベストプラクティスに従ってください。

JavaScriptを使用して、同じIDを持つArray要素を1つのオブジェクトにマージする方法は? JavaScriptを使用して、同じIDを持つArray要素を1つのオブジェクトにマージする方法は? Apr 04, 2025 pm 05:09 PM

同じIDを持つ配列要素をJavaScriptの1つのオブジェクトにマージする方法は?データを処理するとき、私たちはしばしば同じIDを持つ必要性に遭遇します...

Zustand非同期操作:UseStoreが取得した最新の状態を確保する方法は? Zustand非同期操作:UseStoreが取得した最新の状態を確保する方法は? Apr 04, 2025 pm 02:09 PM

Zustand非同期操作のデータの更新問題。 Zustand State Management Libraryを使用する場合、非同期操作を不当にするデータ更新の問題に遭遇することがよくあります。 �...

See all articles