JavaScript ES6의 새로운 클래스 구문 실습 탭에 대한 자세한 설명

巴扎黑
풀어 주다: 2017-09-04 10:34:11
원래의
1522명이 탐색했습니다.

아래 편집기는 일련의 js es6 튜토리얼 - 새로운 클래스 구문 실습 탭(자세한 설명)을 제공합니다. 편집자님이 꽤 좋다고 생각하셔서 지금 공유하고 모두에게 참고용으로 드리고자 합니다. 에디터를 따라가서 살펴볼까요

사실 es6의 객체지향 원리와 메커니즘 중 많은 부분은 여전히 ​​ES5의 그것들이지만 구문은 예전 백엔드 언어와 비슷한 객체지향 구문으로 변경되었습니다 ​​​​php와 java의.

1. es6을 사용하면 기본 클래스를 캡슐화합니다


class Person{
   constructor( uName ){
    this.userName = uName;
   }
   sayName(){
    return this.userName;
   }
  }
로그인 후 복사

PHP와 Java의 클래스와 매우 유사합니까? 사실 본질은 여전히 ​​프로토타입인가요?

먼저 문법 규칙에 대해 이야기해 보겠습니다.

class Person in은 사용자 정의할 수 있는 클래스 이름입니다.

constructor는 키워드입니다. 객체가 인스턴스화되면 이 생성자가 자동으로 호출됩니다.


let oP = new Person( 'ghostwu' );
  console.log( oP.sayName() ); //ghostwu

  console.log( oP instanceof Person ); //true
  console.log( oP instanceof Object ); //true
 
  console.log( typeof Person ); //function
  console.log( typeof Person.prototype.sayName ); //function
  console.log( oP.__proto__ === Person.prototype ); //true
  console.log( 'sayName' in oP ); //true 
  console.log( Person.prototype );
로그인 후 복사

라인 1과 2의 인스턴스 변환 및 호출 방법은 여전히 ​​es5와 동일합니다. class(Person)과 Object. 결과는 es5와 같습니다. 이때 Person의 본질이 함수인지 확실히 생각해 보겠습니다.

Person 클래스가 본질적으로 함수인지 확인합니다.

라인 8에서는 sayName 함수가 실제로 Person의 프로토타입 객체에 추가되는 것을 볼 수 있습니다.

라인 9에서는 여전히 es5 프로토타입 체인을 확인합니다. 특징: 객체의 암시적 프로토타입이 생성자의 프로토타입 객체를 가리킵니다.

Line 10은 프로토타입 체인을 통해 oP 객체가 sayName 메소드를 찾는 것을 확인합니다

이런 종류의 구문을 구문 설탕이라고 하며 본질은 여전히 ​​프로토타입 체인입니다

2. 기본 클래스 사용법을 사용하여 덧셈 연산을 캡슐화합니다.

class Operator{
   constructor( n1 = 1, n2 = 2 ){
    this.num1 = n1;
    this.num2 = n2;
   }
   add( n1 = 10, n2 = 20 ){
    let num1 = n1 || this.num1, num2 = n2 || this.num2;
    return num1 + num2;
   }
  }
  var oper = new Operator();
  console.log( oper.add( 100, 200 ) );
로그인 후 복사


3. 기본 클래스 구문을 사용하여 클래식 탭을 캡슐화합니다.

css 코드:

#tab p {
   width: 200px;
   height: 200px;
   border: 1px solid #000;
   display: none;
  }

  #tab p:nth-of-type(1) {
   display: block;
  }

  .active {
   background: yellow;
  }
로그인 후 복사

html 코드:

<p id="tab">
  <input type="button" value="点我1" data-target="#p1" class="active">
  <input type="button" value="点我2" data-target="#p2">
  <input type="button" value="点我3" data-target="#p3">
  <input type="button" value="点我4" data-target="#p4">
  <p id="p1">1</p>
  <p id="p2">2</p>
  <p id="p3">3</p>
  <p id="p4">4</p>
 </p>
로그인 후 복사

자바스크립트 코드:

window.onload = () => {
   class Tab {
    constructor( context ) {
     let cxt = context || document;
     this.aInput = cxt.querySelectorAll( "input" );
     this.ap = cxt.querySelectorAll( "p" );
    }
    bindEvent(){
     let targetId = null;
     this.aInput.forEach(( ele, index )=>{
      ele.addEventListener( "click", ()=>{
       targetId = ele.dataset.target;
       this.switchTab( ele, targetId );
      });
     });
    }
    switchTab( curBtn, curId ){
     let op = document.querySelector( curId );
     this.ap.forEach(( ele, index )=>{
      ele.style.display = &#39;none&#39;;
      this.aInput[index].className = &#39;&#39;;
     });
     curBtn.className = &#39;active&#39;;
     op.style.display = &#39;block&#39;;
    }
   }
   new Tab( document.querySelector( "#tab" ) ).bindEvent();
  }
로그인 후 복사

위 내용은 JavaScript ES6의 새로운 클래스 구문 실습 탭에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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