0821開発ログ


学習内容


コンストラクション関数,prototype,this(1),(2)

githubのコミット

コンストラクタ

  • オブジェクト向けプログラミング(OOP - Object Oriented Programming)
  • 構造関数:頭文字大文字
  • ジェネレータ関数では、インスタンス自体の
  • を指す.
    function Heroes(name, age) {
        this.name = name;
        this.age = age;
    };
    
    // 인스턴스 = new 함수이름(인자)
    var superMan = new Heroes('Super Man', 30);
    var blackWidow = new Heroes('Black Widow', 34);

    インスタンスの作成方法

    function Person(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    
        this.fullName = function() {
            console.log(this.firstName + " " + this.lastName);
        }
    }
    var lee = new Person('Yesol', 'Lee');
    var heo = new Person('JuYeon', 'Heo');
    
    heo.fullName();

    prototype

  • Personジェネレータ関数を作成すると、Person.prototypeオブジェクト
  • が作成されます.
    fullName()メソッドを
  • プロトタイプ
  • に追加
  • Person.プロトタイプ祖先を継承する方法は
  • を使用できます.
  • 単一インスタンスでメモリを節約する方法はありません
  • すべてのオブジェクトが同じプロパティを持つ部分(
  • メソッドなど)は、プロトタイプに適用されます.
    function Person(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    Person.prototype.fullName = function () {
        console.log(this.firstName + " " +this.lastName);
    }
    
    // 인스턴스: 후손. 생성자 안 메서드 없어도 prototype의 메서드 사용 가능
    var heo = new Person('JuYeon', 'Heo');
    
    heo.fullName();

    protoとconstructor


    proto:インスタンスの祖先を参照する(prototype)

  • インスタンスのプロトタイプ=インスタンスを見つけます.proto
  • ジェネレータによって作成された文字列は、データ型が文字列ではないオブジェクトです.
  • JavaScriptすべてのオブジェクトがオブジェクトです.原型の子孫
  • prototype:コンストラクション関数とともに作成されたオブジェクト

  • ジェネレータ関数を作成すると、その後作成されるすべてのインスタンスの祖先(instance.proto)になるプロトタイプオブジェクトが作成されます.
  • constructor:インスタンスのコンストラクション関数のプロパティを表示

  • インスタンスのコンストラクション関数=インスタンスを見つけます.constructor
  • // 생성자 함수
    function Person (firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    // 생성자 함수로 인스턴스 생성
    var lee = new Person('Yesol', 'Lee');
    
    console.log(lee.__proto__ === Person.prototype); // true
    console.log(Person.prototype.__proto__ === Object.prototype); // true
    console.log(lee.__proto__ === Object.prototype); // false 중간단계 뛰어넘기 불가능
    
    console.log(Person.__proto__ == Function.prototype); // true
    console.log(Function.prototype.__proto__ === Object.prototype); // true
    
    // 인스턴스와 prototype은 모두 생성자함수로 만들어 진 객체
    console.log(lee.constructor === Person); // true
    console.log(Person.prototype.constructor === Person);

    this


    この場合の数:thisを含む場所によって、ターゲットが異なる

  • 一般関数thi->window(ブラウザ)
  • ネスト関数thi->window(ブラウザ):ネスト関数では、thisはwindow
  • と無条件です.
  • イベントのthis->イベントオブジェクト
  • オブジェクトメソッドのthis->オブジェクト
  • メソッドスキーマ関数thi->window(ブラウザ)
  • 一般関数、ネスト関数という例

    function a () {
        console.log(this);
        function b () {
            console.log(this);
        }
        b(); // this = window
    };
    a(); // this = window

    イベントのthis

    var btn_prev = document.querySelector('.btn-prev');
    btn_prev.addEventListener('click', function() {
        console.log(this); // this = btn_prev
    });

    方法

    var obj = {
        age: 54,
        sum: function () {
            console.log(this.age); // this = obj
          
            function c () {
                console.log(this); // 중첩함수라서 this = window
            }
            c(); 
        }
    };
    obj.sum();

    ネストされた関数のthisもオブジェクトを指す場合:thisを変数に保存

    var obj = {
        age: 54,
        sum: function () {
            console.log(this.age);
            var that = this;
    
            function c () {
                console.log(that);
            }
            c(); // 중첩함수라서 this = window
        }
    };
    obj.sum();

    練習1:作成者の使用

  • 昨日の画像リスト情報を含む画像オブジェクト
  • を作成するには、コンストラクション関数を使用します.
    var arr = [];
    var i = 0;
    // 이미지 정보 객체 생성자 함수
    function NatureImage(name, img, txt) {
        this.name = name;
        this.img = img;
        this.txt = txt;
    }
    // 생성자 함수로 이미지 인스턴스 만들어 배열에 삽입
    function createNatureImage (name, img, txt) {
        var fullImg = `img/img-${img}.jpg`;
        var natureImage = new NatureImage(name, fullImg, txt);
        arr.push(natureImage);
    };
    
    createNatureImage('nature 1 name', 1 , 'nature 1 description');
    createNatureImage('nature 2 name', 2 , 'nature 2 description');
    ...

    実習。


    時間ごとに無限に繰り返される関数の作成:settimeOut(f(x)、timeを使用)

  • %の余剰演算の特徴を用いて,インデックス値が無限に増加しても,配列インデックス値内で電流を無限に繰り返す.
  • settimeOut()関数の内部でloop()関数自体を再呼び出し、2秒ごとに無限に繰り返すことができます.
  • var arr = [10, 20, 30];
    var index = 0; // 기준점
    
    function loop() {
        var current = index % arr.length; // 0 % 3 = 0
        console.log(arr[current]);
        index++;
    
        setTimeout(function() {
            loop()
        }, 2000);
    }
    loop();

    2.単語ごとに配列内の単語を作成、削除する


    1.インポートする単語のリストをインポートし、単語のhtmlラベルをポップアップします。

    var words = ['엔드게임', '인피니티 워', '에이지 오브 울트론'];
    var txtElement = document.getElementById('txt');

    2.作業に必要な属性を持つコンストラクション関数を作成して呼び出します。

    function TypeWriter(txtElement, words) {
        this.txtElement = txtElement; // html 태그
        this.words = words; // 단어 리스트
    
        this.txt = ""; // 출력할 텍스트
        this.wordIndex = 0; // 리스트에서 가져올 단어 인덱스
        this.isDeleting = false; // 현재 작성 중/삭제 중인지 
    
        this.type(); // 실제 작성하는 함수 실행시켜 둠
    };
    
    // 인스턴스 없어도 생성자 함수 호출 가능
    new TypeWriter(txtElement, words);

    3.プロトタイプのtype関数を作成する

  • は作成中であり、削除中の状態に応じて配列から必要な部分を切り取り、
  • にインポートする.
    TypeWriter.prototype.type = function() {
      // 현재 배열 안 데이터 가져오기
      var current = this.wordIndex % this.words.length;
      var fullTxt = this.words[current];
    
      // 각 단어에서 필요한 부분만 잘라서 가져오기
      // substring(start, end): start부터 end 직전까지. 인자 1개면 start 이후부터 가져오기
      if(this.isDeleting) {
        this.txt = fullTxt.substring(0, this.txt.length - 1);
      } else {
        this.txt = fullTxt.substring(0, this.txt.length + 1); // 글자수보다 1개 더까지 잘라내기
      }
      this.txtElement.textContent = this.txt;
    }
  • //文字が完了した場合、すべての文字を削除するとステータス
  • が変更されます.
    if(!this.isDeleting && this.txt === fullTxt) {
      this.isDeleting = true;
    
    } else if (this.isDeleting && this.txt === ""){
      this.isDeleting = false;
      this.wordIndex++; // 다음 단어로 넘어가기
    }
  • 自己呼
  • 元コードは無限に繰り返されるが、wordIndexを使用して停止点を追加した.
  • var that = this; // 중첩함수 안에서도 객체 선택하기 위한 코드
    
    setTimeout(function() {
      console.log(that);
    
      // 멈추는 지점 추가
      if(that.wordIndex<5) {
        that.type();
      }
    
    }, 500);

    その他


    Templete Literal:backtic(`)を使用した文字列の作成(ES 6)

  • backticスキーマ文字列を使用すると、js変数は${}に記入できます.
  • var name = 'mango';
    console.log("my name is " + name);
    console.log(`my name is ${name}.`);

    難点

  • ジェネレータ関数、__proto__prototypeconstructorなどの特定の属性またはオブジェクトおよびその属性の検索方法が混在しており、混同されている.
  • の最後の文字列順で示す練習課題を行うのは,生成者などの練習のために構成された問題であるかもしれないが,解答過程は斬新である.もし私がただ問題を解くだけなら、思い出せません.
  • 解決策

  • の各概念の属性と目的を明確に区別した.
  • の他の方向の解題方法をマスターしたと思います.
  • 感想


    html、cssを使用する場合とは異なり、より多くの論理プロセスが必要だと思います.これは、デザインとは異なり、ある程度の順序性機能を体現しているからだと思います.早く進捗状況を出て、サイト機能を作成してみたいです.