찾다

JS의 OOP

Aug 29, 2024 pm 01:39 PM

OOP in JS

패러다임은 코드 스타일, 코드 구성 방식을 나타냅니다. 일반적인 프로그래밍 패러다임은 OOP, Functional 등입니다. 개발자가 되려면 OOP를 잘 알아야 합니다.

  • 가장 인기 있는 엔터프라이즈 프로그래밍 패러다임
  • 객체 기준
  • 코드 정리를 목표로 개발
  • 코드를 더욱 유연하고 유지 관리하기 쉽게 만듭니다.
  • OOP 이전에는 코드가 구조 없이 전역 범위의 여러 fn에 분산되어 있었습니다. 그 스타일은 유지 관리가 매우 어려운 스파게티 코드라고 불리며, 새로운 기능을 추가하는 것을 잊어버리게 됩니다.
  • 코드를 통해 객체를 생성하는 데 사용됩니다.
  • 객체간 상호작용도 가능합니다.

API

  • 객체 외부의 코드가 액세스하여 다른 객체와 통신하는 데 사용할 수 있는 메서드입니다.

수업

  • 객체를 생성하기 위한 추상 청사진.
  • 클래스에서 인스턴스화됩니다. 즉, 클래스 청사진을 사용하여 생성됩니다.
  • 'new Class()' 구문을 사용하여 클래스에서 여러 객체가 생성됩니다

수업 디자인:

  • OOP의 4가지 원리인 추상화, 캡슐화, 상속, 다형성을 사용하여 수행되었습니다
  • 추상화: 최종 사용자에게 중요하지 않은 불필요한 세부정보를 숨깁니다.
  • 캡슐화: 일부 속성-메서드를 비공개로 유지하여 클래스 내부에서만 액세스할 수 있게 하고 클래스 외부에서는 액세스할 수 없게 만듭니다. 외부 세계와 상호 작용하기 위한 공용 인터페이스 API로 몇 가지 메서드를 노출합니다. 따라서 외부 코드가 내부 상태[객체의 데이터]를 조작하는 것을 방지합니다. 이는 버그의 큰 소스가 될 수 있기 때문입니다. 공개 인터페이스는 비공개가 아닌 코드입니다. 메소드를 비공개로 설정하면 외부 종속성을 손상하지 않고 코드 구현을 더 쉽게 변경할 수 있습니다. 요약: 상태와 메서드를 훌륭하게 캡슐화하고 필수 메서드만 공개합니다.
  • 상속: 중복된 코드는 유지 관리가 어렵습니다. 따라서 이 개념은 이미 작성된 코드를 상속함으로써 코드의 재사용성을 지원합니다. 하위 클래스는 상위 클래스의 모든 속성 및 메서드를 상속하여 상위 클래스를 확장합니다. 또한 하위 클래스는 상속된 기능과 함께 자체 데이터 기능을 구현합니다.
  • 다형성: 하위 클래스는 상위 클래스에서 상속된 메서드를 덮어쓸 수 있습니다.

객체는 다음과 같습니다.

  • 실제 세계 또는 추상적인 특징을 모델링하는 데 사용됩니다.
  • 데이터(속성)와 코드(메서드)가 포함될 수 있습니다. 데이터와 코드를 하나의 블록에 담을 수 있도록 도와주세요
  • 독립적인 코드 조각/블록.
  • 앱의 구성 요소가 서로 상호작용합니다.
  • 객체와의 상호작용은 공개 인터페이스 API를 통해 이루어집니다.
  • 클래스에서 생성된 모든 개체를 해당 클래스의 인스턴스라고 합니다.
  • 모든 객체는 서로 다른 데이터를 가질 수 있지만 모두 공통 기능을 공유합니다

고전적 상속:

  • Java, C++, Python 등에서 지원
  • 한 클래스가 다른 클래스에서 상속됨
  • 메서드나 동작은 클래스에서 모든 인스턴스로 복사됩니다.

JS의 위임 또는 프로토타입 상속:

  • 고전 언어와 마찬가지로 모든 OOP 원칙을 지원합니다.
  • 클래스에서 상속되는 인스턴스.
  • 프로토타입에는 해당 프로토타입에 연결된 모든 개체에 액세스할 수 있는 모든 메서드가 포함되어 있습니다. 프로토타입: 메서드 포함 object: 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 - 연도); };

mike.calcAge(1970); // 54
mona.calcAge(1940); // 84

  • mike 개체에는 .calcAge()가 포함되어 있지 않지만 Person.prototype 개체에 정의된 proto 링크를 사용하여 액세스합니다.
  • 'this'는 항상 함수를 호출하는 객체로 설정됩니다.

마이크.프로토; // { calcAge: [함수(익명)] }
모나.프로토; // { calcAge: [함수(익명)] }

mike.proto === Person.prototype; //참

  • 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
JavaScript : 웹 언어의 다양성 탐색JavaScript : 웹 언어의 다양성 탐색Apr 11, 2025 am 12:01 AM

JavaScript는 현대 웹 개발의 핵심 언어이며 다양성과 유연성에 널리 사용됩니다. 1) 프론트 엔드 개발 : DOM 운영 및 최신 프레임 워크 (예 : React, Vue.js, Angular)를 통해 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축합니다. 2) 서버 측 개발 : Node.js는 비 차단 I/O 모델을 사용하여 높은 동시성 및 실시간 응용 프로그램을 처리합니다. 3) 모바일 및 데스크탑 애플리케이션 개발 : 크로스 플랫폼 개발은 개발 효율을 향상시키기 위해 반응 및 전자를 통해 실현됩니다.

JavaScript의 진화 : 현재 동향과 미래 전망JavaScript의 진화 : 현재 동향과 미래 전망Apr 10, 2025 am 09:33 AM

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

Demystifying JavaScript : 그것이하는 일과 중요한 이유Demystifying JavaScript : 그것이하는 일과 중요한 이유Apr 09, 2025 am 12:07 AM

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

Python 또는 JavaScript가 더 좋습니까?Python 또는 JavaScript가 더 좋습니까?Apr 06, 2025 am 12:14 AM

Python은 데이터 과학 및 기계 학습에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명하며 데이터 분석 및 웹 개발에 적합합니다. 2. JavaScript는 프론트 엔드 개발의 핵심입니다. Node.js는 서버 측 프로그래밍을 지원하며 풀 스택 개발에 적합합니다.

JavaScript를 어떻게 설치합니까?JavaScript를 어떻게 설치합니까?Apr 05, 2025 am 12:16 AM

JavaScript는 이미 최신 브라우저에 내장되어 있기 때문에 설치가 필요하지 않습니다. 시작하려면 텍스트 편집기와 브라우저 만 있으면됩니다. 1) 브라우저 환경에서 태그를 통해 HTML 파일을 포함하여 실행하십시오. 2) Node.js 환경에서 Node.js를 다운로드하고 설치 한 후 명령 줄을 통해 JavaScript 파일을 실행하십시오.

Quartz에서 작업이 시작되기 전에 알림을 보내는 방법은 무엇입니까?Quartz에서 작업이 시작되기 전에 알림을 보내는 방법은 무엇입니까?Apr 04, 2025 pm 09:24 PM

쿼츠 타이머를 사용하여 작업을 예약 할 때 미리 쿼츠에서 작업 알림을 보내는 방법 작업의 실행 시간은 CRON 표현식에 의해 설정됩니다. 지금...

JavaScript에서 생성자의 프로토 타입 체인에서 함수의 매개 변수를 얻는 방법은 무엇입니까?JavaScript에서 생성자의 프로토 타입 체인에서 함수의 매개 변수를 얻는 방법은 무엇입니까?Apr 04, 2025 pm 09:21 PM

JavaScript 프로그래밍에서 JavaScript의 프로토 타입 체인에서 함수 매개 변수를 얻는 방법 프로토 타입 체인의 기능 매개 변수를 이해하고 조작하는 방법은 일반적이고 중요한 작업입니다 ...

Wechat Mini 프로그램 웹 뷰에서 Vue.js 동적 스타일 변위가 실패한 이유는 무엇입니까?Wechat Mini 프로그램 웹 뷰에서 Vue.js 동적 스타일 변위가 실패한 이유는 무엇입니까?Apr 04, 2025 pm 09:18 PM

WeChat 애플릿 웹 뷰에서 vue.js를 사용하는 동적 스타일 변위 실패가 vue.js를 사용하는 이유를 분석합니다.

See all articles

핫 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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.