자바스크립트에는 상속이 있나요?

WBOY
풀어 주다: 2022-04-08 10:21:38
원래의
1791명이 탐색했습니다.

JavaScript에는 상속이 있습니다. JavaScript 상속은 기존 클래스를 기반으로 새 클래스를 생성할 수 있는 메커니즘입니다. 상속을 통해 상위 클래스의 메서드와 변수를 재사용할 수 있으며 프로토타입 체인과 생성자를 사용하여 상속을 얻을 수 있습니다.

자바스크립트에는 상속이 있나요?

이 튜토리얼의 운영 환경: Windows 10 시스템, JavaScript 버전 1.8.5, Dell G3 컴퓨터.

JavaScript에 상속이 있나요?

JavaScript에 상속이 있나요?

JavaScript 상속은 기존 클래스를 기반으로 새 클래스를 생성할 수 있는 메커니즘으로, 하위 클래스가 상위 클래스의 메서드와 변수를 재사용할 수 있는 유연성을 제공합니다. 상속과정은 일반에서 특수로 넘어가는 과정이다.

JavaScript에서 상속을 구현하는 방법은 무엇입니까?

1. 프로토타입 체인

기본 아이디어: 프로토타입을 사용하여 하나의 참조 유형이 다른 참조 유형의 속성과 메서드를 상속하도록 합니다.

생성자, 프로토타입 및 인스턴스 간의 관계: 각 생성자에는 프로토타입 개체가 있고, 프로토타입 개체에는 생성자에 대한 포인터가 포함되어 있으며, 인스턴스에는 프로토타입 개체에 대한 내부 포인터가 포함되어 있습니다.

프로토타입 체인 구현 상속 예:

function SuperType() { this.property = true; } SuperType.prototype.getSuperValue = function() { return this.property; } function subType() { this.property = false; } //继承了SuperType SubType.prototype = new SuperType(); SubType.prototype.getSubValue = function (){ return this.property; } var instance = new SubType(); console.log(instance.getSuperValue());//true
로그인 후 복사

2. 생성자 차용

기본 아이디어: 하위 유형 생성자 내에서 슈퍼클래스 생성자를 호출하고 call() 및 apply() 메서드를 사용하여 새 생성자를 실행합니다. 개체.

예:

function SuperType() { this.colors = ["red","blue","green"]; } function SubType() { SuperType.call(this);//继承了SuperType } var instance1 = new SubType(); instance1.colors.push("black"); console.log(instance1.colors);//"red","blue","green","black" var instance2 = new SubType(); console.log(instance2.colors);//"red","blue","green"
로그인 후 복사

3. 조합 상속

기본 아이디어: 프로토타입 연결 기술과 생성자 차용 기술을 결합하여 두 기술의 장점을 모두 활용하는 상속 패턴입니다.

예:

function SuperType(name) { this.name = name; this.colors = ["red","blue","green"]; } SuperType.prototype.sayName = function() { console.log(this.name); } function SubType(name, age) { SuperType.call(this,name);//继承属性 this.age = age; } //继承方法 SubType.prototype = new SuperType(); Subtype.prototype.constructor = Subtype; Subtype.prototype.sayAge = function() { console.log(this.age); } var instance1 = new SubType("EvanChen",18); instance1.colors.push("black"); consol.log(instance1.colors);//"red","blue","green","black" instance1.sayName();//"EvanChen" instance1.sayAge();//18 var instance2 = new SubType("EvanChen666",20); console.log(instance2.colors);//"red","blue","green" instance2.sayName();//"EvanChen666" instance2.sayAge();//20
로그인 후 복사

4. 프로토타입 상속

기본 아이디어: 프로토타입의 도움으로 기존 개체를 기반으로 새 개체를 만들 수 있으며 사용자 정의 유형을 만들 필요가 없습니다.

프로토타입 상속 개념은 다음 함수로 설명할 수 있습니다.

function object(o) { function F(){} F.prototype = o; return new F(); }
로그인 후 복사

예:

var person = { name:"EvanChen", friends:["Shelby","Court","Van"]; }; var anotherPerson = object(person); anotherPerson.name = "Greg"; anotherPerson.friends.push("Rob"); var yetAnotherPerson = object(person); yetAnotherPerson.name = "Linda"; yetAnotherPerson.friends.push("Barbie"); console.log(person.friends);//"Shelby","Court","Van","Rob","Barbie"
로그인 후 복사

ECMAScript5는 새로운 Object.create() 메서드를 통해 프로토타입 상속을 표준화합니다. 이 메서드는 두 개의 매개변수를 받습니다. 하나는 매개변수로 사용됩니다. 새 객체의 프로토타입 객체와 추가 속성을 새 객체로 정의하는 객체입니다.

var person = { name:"EvanChen", friends:["Shelby","Court","Van"]; }; var anotherPerson = Object.create(person); anotherPerson.name = "Greg"; anotherPerson.friends.push("Rob"); var yetAnotherPerson = Object.create(person); yetAnotherPerson.name = "Linda"; yetAnotherPerson.friends.push("Barbie"); console.log(person.friends);//"Shelby","Court","Van","Rob","Barbie"
로그인 후 복사

5. 기생 상속

기본 아이디어: 내부적으로 객체를 향상시키는 상속 프로세스를 캡슐화하는 함수를 만들고, 마침내 모든 작업 객체를 수행한 것처럼 반환합니다.

예:

function createAnother(original) { var clone = object(original); clone.sayHi = function () { alert("hi"); }; return clone; } var person = { name:"EvanChen", friends:["Shelby","Court","Van"]; }; var anotherPerson = createAnother(person); anotherPerson.sayHi();///"hi"
로그인 후 복사

6. 기생 결합 상속

기본 아이디어: 함수를 빌려 속성을 상속하고 프로토타입 체인의 혼합 형태를 통해 메서드를 상속합니다.

기본 모델은 다음과 같습니다.

function inheritProperty(subType, superType) { var prototype = object(superType.prototype);//创建对象 prototype.constructor = subType;//增强对象 subType.prototype = prototype;//指定对象 }
로그인 후 복사

예:

function SuperType(name){ this.name = name; this.colors = ["red","blue","green"]; } SuperType.prototype.sayName = function (){ alert(this.name); }; function SubType(name,age){ SuperType.call(this,name); this.age = age; } inheritProperty(SubType,SuperType); SubType.prototype.sayAge = function() { alert(this.age); }
로그인 후 복사

관련 추천:javascript 학습 튜토리얼

위 내용은 자바스크립트에는 상속이 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!