JavaScript의 링크 호출 상세 정보

체인 모드
체인 모델은 일종의 체인 호출 방식으로 정확하게 말하면 통상적으로 정의된 디자인 모델 범주에 속하지 않지만 체인 호출은 매우 유용한 코드 구축 기교이다.
묘사
체인 호출은 JavaScript 언어에서 흔히 볼 수 있다. 예를 들어 jQuery, Promise 등은 모두 체인 호출을 사용한다. 우리가 같은 대상을 여러 번 호출할 때 우리는 여러 번 그 속성이나 방법을 써야 한다.또는 () 조작, 체인 호출은 이 과정을 간소화하는 인코딩 방식으로 코드를 간결하고 쉽게 읽을 수 있다.
체인식 호출은 일반적으로 다음과 같은 몇 가지 실현 방식이 있지만 본질적으로 비슷하며 모두 대상을 되돌려 제공한 후에 호출한다.
  • this의 작용역 체인, jQuery의 실현 방식, 통상적인 체인 호출은 모두 이런 방식을 채택한다..
  • 반환 대상 자체,this와 차이점은 반환 체인식 대상을 표시하는 것이다..
  • 패키지를 닫고 대상을 되돌리는 방식이 실현되는데 이런 방식은 콜리화와 비슷한 점이 있다..
  • 
    var Person = function() {};
    Person.prototype.setAge = function(age){
      this.age = age; 
      return this;
    }
    Person.prototype.setWeight = function(weight){
      this.weight = weight; 
      return this;
    }
    Person.prototype.get = function(){
      return `{age: ${this.age}, weight: ${this.weight}}`;
    }
    
    var person = new Person();
    var des = person.setAge(10).setWeight(30).get();
    console.log(des); // {age: 10, weight: 30}
    
    var person = {
      age: null,
      weight: null,
      setAge: function(age){
        this.age = age; 
        return this;
      },
      setWeight: function(weight){
        this.weight = weight; 
        return this;
      },
      get: function(){
        return `{age: ${this.age}, weight: ${this.weight}}`;
      }
    };
    var des = person.setAge(10).setWeight(30).get();
    console.log(des); // {age: 10, weight: 30}
    
    function numsChain(num){
      var nums = num;
      function chain(num){
        nums = `${nums} -> ${num}`;
        return chain;
      }
      chain.get = () => nums;
      return chain;
    }
    var des = numsChain(1)(2)(3).get();
    console.log(des); // 1 -> 2 -> 3
    체인 조작부호 (옵션)
    체인 호출에 대해 말하자면, ES2020의 새로운 특성 연산자에 속하는 자바스크립트의 선택적 체인 조작부호를 말할 필요가 있다.옵션 체인 조작부호?.연결 대상 체인 깊숙한 곳에 있는 속성의 값을 읽을 수 있습니다. 체인의 모든 인용이 유효한지 명확하게 검증할 필요가 없습니다.?...조작부호의 기능은 유사하다.체인식 조작부호는 빈 nullish 즉null 또는undefined로 인용된 상황에서 오류를 일으키지 않습니다. 이 표현식 단락 반환값은undefined입니다.함수 호출과 함께 사용할 때, 주어진 함수가 존재하지 않으면undefined를 되돌려줍니다.존재하지 않을 수 있는 대상 속성에 접근하려고 시도할 때, 체인 조작부호를 선택하면 표현식을 더욱 짧고 간단명료하게 할 수 있습니다.대상의 내용을 탐색할 때 어떤 속성이 반드시 존재하는지 확인할 수 없다면 체인 조작부호를 선택하는 것도 도움이 된다.
    문법
    
    obj?.prop
    obj?.[expr]
    arr?.[index]
    func?.(args)
    예제
    
    const obj = {a: {}};
    console.log(obj.a); // {}
    console.log(obj.a.b); // undefined
    // console.log(obj.a.b.c); // Uncaught TypeError: Cannot read property 'c' of undefined
    console.log(obj && obj.a); // {}
    console.log(obj && obj.a && obj.a.b && obj.a.b.c); // undefined
    console.log(obj?.a?.b?.c); // undefined
    
    const test = void 0;
    const prop = "a";
    console.log(test); // undefined
    console.log(test?.a); // undefined
    console.log(test?.[prop]); // undefined
    console.log(test?.[0]); // undefined
    console.log(test?.()); // undefined
    jQuery의 체인 호출
    jQuery는 고급스럽고 럭셔리한 프레임워크입니다. 그 중에서 매우 훌륭한 방법과 논리가 있습니다. 현재 Vue,React와 유사한 MVVM 모델의 프레임워크가 유행하지만 jQuery의 디자인은 정말 훌륭하고 배울 만합니다. 여기서 가장 기초적인 실례화된 jQuery를 예로 들어 jQuery가this를 통해 어떻게 체인식으로 호출되는지 알아보겠습니다.
    먼저 가장 기본적인 종류를 정의하고 원형 체인을 통해 계승하는 방법을 제시한다.
    
    function _jQuery(){}
    _jQuery.prototype = {
      constructor: _jQuery,
      length: 2,
      size: function(){
        return this.length;
      }
    }
    
    var instance = new _jQuery();
    console.log(instance.size()); // 2
    // _jQuery.size() // Uncaught TypeError: _jQuery.size is not a function
    // _jQuery().size() / /Uncaught TypeError: Cannot read property 'size' of undefined
    하나의 클래스를 정의하고 실례화한 후에 실례 간에 원형적인 방법을 공유할 수 있고 직접_jQuery 클래스를 직접 호출하면 안 됩니다. 첫 번째 이상은 _jQuery 클래스에는 정적 방법이 없습니다. 두 번째 이상은 _jQuery는 함수로 실행된 후 값을 되돌려 주지 않습니다. 여기서 jQuery가 $() 방식으로 호출될 때 여러 가지 방법을 포함하는 대상을 되돌려 줍니다. 자신만으로는 접근할 수 없습니다. 우리는 다른 변수를 빌려 접근합니다.
    
    function _jQuery(){
      return _fn;
    }
    var _fn = _jQuery.prototype = {
      constructor: _jQuery,
      length: 2,
      size: function(){
        return this.length;
      }
    }
    console.log(_jQuery().size()); // 2
    실제로 jQuery는 변수 생성을 줄이기 위해 _fn이 보기에는_jQuery의 속성입니다.
    
    function _jQuery(){
      return _jQuery.fn;
    }
    _jQuery.fn = _jQuery.prototype = {
      constructor: _jQuery,
      length: 2,
      size: function(){
        return this.length;
      }
    }
    console.log(_jQuery().size()); // 2
    여기까지는 확실해_jQuery () 방식은 원형의 방법을 호출하지만, jQuery에서 $() 의 주요 목표는 선택기로 원소를 선택하는 것입니다. 현재 되돌아오는 것은 _jQuery.fn 대상은 분명히 요구에 미치지 못한다. 되돌아오는 원소를 얻기 위해 원형에 init 방법을 정의하여 원소를 얻는다. 여기는 일을 줄이기 위해document를 직접 사용한다.query Selector, 실제로 jQuery의 선택기 구축은 매우 복잡하다.
    
    function _jQuery(selector){
      return _jQuery.fn.init(selector);
    }
    _jQuery.fn = _jQuery.prototype = {
      constructor: _jQuery,
      init: function(selector){
        return document.querySelector(selector);
      },
      length: 3,
      size: function(){
        return this.length;
      }
    }
    console.log(_jQuery("body")); // <body>...</body>
    이렇게 체인식으로 호출된this를 빠뜨린 것 같습니다. 여기서this의 지향을 이용해야 합니다. 호출할 때this는 항상 호출된 대상을 가리키기 때문에 선택한 요소를this 대상에 마운트하면 됩니다.
    
    function _jQuery(selector){
      return _jQuery.fn.init(selector);
    }
    _jQuery.fn = _jQuery.prototype = {
      constructor: _jQuery,
      init: function(selector){
        this[0] = document.querySelector(selector);
        this.length = 1;
        return this;
      },
      length: 3,
      size: function(){
        return this.length;
      }
    }
    var body = _jQuery("body");
    console.log(body); // {0: body, length: 1, constructor: ƒ, init: ƒ, size: ƒ}
    console.log(body.size()); // 1
    console.log(_jQuery.fn); // {0: body, length: 1, constructor: ƒ, init: ƒ, size: ƒ}
    하지만 이때 또 하나의 문제가 발생했습니다. 우리의 선택기가 선택한 요소는 바로 마운트되었습니다_jQuery.fn에서 이렇게 하면 원형이 공유되기 때문에 다음에 정의된 선택기는 앞에 정의된 선택기를 덮어씁니다. 그러면 안 됩니다. 그래서 new 조작부호를 사용하여 대상을 새로 만듭니다.
    
    function _jQuery(selector){
      return new _jQuery.fn.init(selector);
    }
    _jQuery.fn = _jQuery.prototype = {
      constructor: _jQuery,
      init: function(selector){
        this[0] = document.querySelector(selector);
        this.length = 1;
        return this;
      },
      length: 3,
      size: function(){
        return this.length;
      }
    }
    var body = _jQuery("body");
    console.log(body); // init {0: body, length: 1}
    // console.log(body.size()); // Uncaught TypeError: body.size is not a function
    이렇게 또 문제가 생겼습니다. new 실례화를 사용할 때_jQuery.fn.init 때 되돌아오는 this는 _jQuery.fn.init의 실례, 우리는 체인 호출을 진행할 수 없습니다. jQuery는 매우 교묘한 방법으로 이 문제를 해결했습니다. 직접_jQuery.fn.init의 원형 지향_jQuery.prototype, 순환 인용 문제가 있지만 상대적으로 이 정도의 성능 소모는 아무것도 아닙니다. 이로써 jQuery 선택기와 체인 호출의 실현을 완성했습니다.
    
    function _jQuery(selector){
      return new _jQuery.fn.init(selector);
    }
    _jQuery.fn = _jQuery.prototype = {
      constructor: _jQuery,
      init: function(selector){
        this[0] = document.querySelector(selector);
        this.length = 1;
        return this;
      },
      length: 3,
      size: function(){
        return this.length;
      }
    }
    _jQuery.fn.init.prototype = _jQuery.fn;
    var body = _jQuery("body");
    console.log(body); // init {0: body, length: 1}
    console.log(body.size()); // 1
    console.log(_jQuery.fn.init.prototype.init.prototype.init.prototype === _jQuery.fn); // true
    매일 한 문제
    https://github.com/WindrunnerMax/EveryDay
    이상은 자바스크립트의 체인 호출에 대한 상세한 내용입니다. 자바스크립트의 체인 호출에 대한 더 많은 자료는 저희 다른 관련 글을 주목해 주십시오!

    좋은 웹페이지 즐겨찾기