JavaScript의 클래스 및 인스턴스 구현 방법

PHPz
풀어 주다: 2018-09-29 16:20:23
원래의
1323명이 탐색했습니다.

이 글은 주로 자바스크립트에서 클래스와 인스턴스의 구현 방법을 소개합니다. 클래스와 인스턴스의 구현 과정을 매우 교묘하게 시뮬레이션한 것입니다. 필요한 경우 참조할 수 있습니다.

JavaScript에는 상위 클래스, 하위 클래스 또는 클래스 및 인스턴스 개념이 없습니다. 상속을 실현하기 위해 전적으로 프로토타입 체인에 의존합니다. JavaScript는 객체의 속성을 찾을 때까지 프로토타입 체인을 위쪽으로 순회합니다. 해당 속성을 찾습니다. . JavaScript에서 클래스와 인스턴스의 개념을 시뮬레이션하는 방법은 여러 가지가 있습니다.

1. 생성자를 직접 사용하여 객체를 생성하고 이를 생성자 내부에서 참조합니다.

function Animal() {  
 this.name = "animal";  
 }  
 Animal.prototype.makeSound = function() {  
 console.log("animal sound");  
 }  
[Function]  
 var animal1 = new Animal();  
 animal1.name;  
'animal'  
 animal1.makeSound();  
animal sound
로그인 후 복사

다른 예를 살펴보세요.

function Point(x, y) {  
 this.x = x;  
 this.y = y;  
 }  
 Point.prototype = {  
 method1: function() { console.log("method1"); },  
 method2: function() { console.log("method2"); },  
 }  
{ method1: [Function], method2: [Function] }  
 var point1 = new Point(10, 20);  
 point1.method1();  
method1  
 point1.method2();  
method2
로그인 후 복사

위에서 먼저 생성자 객체의 프로토타입 속성을 지정한 다음 새 인스턴스를 만듭니다. 그런 다음 메소드에 지정된 프로토타입을 호출합니다.

2. Object.create() 메소드를 사용하여 객체를 생성합니다

var Animal = {  
 name: "animal",  
 makeSound: function() { console.log("animal sound"); },  
 }  
 var animal2 = Object.create(Animal);  
 animal2.name;  
'animal'  
 console.log(animal2.name);  
animal  
 animal2.makeSound();  
animal sound
로그인 후 복사

이것은 메서드는 생성자 메서드보다 간단하지만 프라이빗 속성과 프라이빗 메서드를 구현할 수 없고, 인스턴스 객체 간에 데이터를 공유할 수 없으며, 클래스 시뮬레이션이 아직 충분히 포괄적이지 않습니다.

3. 네덜란드 프로그래머 Gabor de Mooij가 제안한 미니멀리스트 권장 사용법

var Animal = {  
 init: function() {  
 var animal = {};  
 animal.name = "animal";  
 animal.makeSound = function() { console.log("animal sound"); };  
 return animal;  
 }  
 };  
 var animal3 = Animal.init();  
 animal3.name;  
'animal'  
 animal3.makeSound();  
animal sound
로그인 후 복사

프로토타입을 사용하지 말고 생성자 초기화만 사용자 정의하면 됩니다. 아주 간단합니다.

var Cat = {  
 init: function() {  
 var cat = Animal.init();  
 cat.name2 = "cat";  
 cat.makeSound = function() { console.log("cat sound"); };  
 cat.sleep = function() { console.log("cat sleep"); };  
 return cat;  
 }  
 }  
 var cat = Cat.init();  
 cat.name; // 'animal'  
 cat.name2; // 'cat'  
 cat.makeSound(); // 类似于方法的重载  
cat sound  
 cat.sleep();  
cat sleep
로그인 후 복사

개인 속성 및 개인 메서드 사용:

var Animal = {  
 init: function() {  
 var animal = {};  
 var sound = "private animal sound"; // 私有属性  
 animal.makeSound = function() { console.log(sound); };  
 return animal;  
 }  
 };  
 var animal4 = Animal.init();  
 Animal.sound; // undefined 私有属性只能通过对象自身的方法来读取.  
 animal.sound; // undefined 私有属性只能通过对象自身的方法来读取  
 animal4.makeSound();  
private animal sound
로그인 후 복사

속성과 메서드가 동물 객체에 정의되지 않는 한, 개인 속성이므로 사용할 수 없습니다.
클래스와 인스턴스 간에 데이터 공유가 가능합니다.

var Animal = {  
 sound: "common animal sound",  
 init: function() {  
 var animal = {};  
 animal.commonSound = function() { console.log(Animal.sound); };  
 animal.changeSound = function() { Animal.sound = "common animal sound changed"; };  
 return animal;  
 }  
 }  
 var animal5 = Animal.init();  
 var animal6 = Animal.init();  
 Animal.sound; // 可以视为类属性  
'common animal sound'  
 animal5.sound; // 实例对象不能访问类属性  
undefined  
 animal6.sound;  
undefined  
 animal5.commonSound();  
common animal sound  
 animal6.commonSound();  
common animal sound  
 animal5.changeSound(); // 修改类属性  
undefined  
 Animal.sound;  
'common animal sound'  
 animal5.commonSound();  
common animal sound  
 animal6.commonSound();  
common animal sound
로그인 후 복사

예를 들어 Animal.sound는 클래스와 인스턴스의 공통 속성으로 클래스로 간주될 수 있습니다.

인스턴스가 공통 속성을 수정하면 그에 따라 클래스와 다른 인스턴스의 공통 속성도 수정됩니다.

요약하면 이것이 개념 및 사용법입니다. 이 기사가 모든 사람의 자바스크립트 프로그래밍에 도움이 되기를 바랍니다. 더 많은 관련 튜토리얼을 보려면 JavaScript 비디오 튜토리얼을 방문하세요.

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