JavaScript 3 풀기: 비동기 코드 - 메서드 체인

이 기사에서는 아직 비동기 코드를 소개하지 않지만 순차 프로그래밍은 실제로 Promise 및 비동기 코드에 대한 좋은 흐름입니다.

시퀀스(체인)의 이전 구성 요소를 기반으로 순서대로 실행되는 구성 요소가 포함된 프로그램입니다.

예: JS의 문자열 연산



"Hello World".split("").reverse().join("")

  // split reverse and join will execute in sequence based on the
  // previous component's(object) result


이러한 함수에 의해 형성된 이 시퀀스 또는 체인은 공식적으로 메서드 체인으로 알려져 있습니다.

메소드 체이닝(MC)



빌드할 MC에 대한 간단하지만 완전하지 않은 설명은 다음과 같습니다. 체인의 메서드에서 메서드로 개체를 전달합니다.

객체에 대해 조금 생각해 봅시다

점 연산 및 개체



Dot Op 예시


.forEach()
.toString()
.call()
.bind()




점 연산은 개체의 속성에 액세스합니다.


const simpleObject = {
  name: "sk"

}



console.log(simpleObject.name)  // sk  - produce by a simple dot op 



JS에서 Dot op의 가정은 매우 간단합니다. Dot op는 작동 중인 모든 것이 객체(런타임 중이든 선언 중이든)라고 가정하고 점의 오른쪽은 왼쪽이 객체라고 가정합니다.

let str = new String("hello")

let arr = new Array()



console.log(typeof str)  // Object 

console.log(typeof arr)  // Object

str.split()
arr.forEach()

// fun fact most primitives in JS are turned to objects during
// runtime, hence it's possible to dot operate on a primitive 
// e.g string  "Hello world".split() 



이 모든 것의 요점은 무엇입니까?

 yAxisG

 .append("text")

 .attr('class', 'axis-label')

 .attr('y', -80)

 .attr('x', -innerHeight / 2)

 .attr('transform', `rotate(-90)`)

 .attr('fill', 'black')

 .attr('text-anchor', 'middle')

 .text(YaxisLabel)





여러분이 보고 있는 것은 JS 시각화 라이브러리인 D3의 스니펫으로, 여러 도트 작업을 연결하고 있습니다. 우리는 도트 ​​작업의 오른쪽이 왼쪽이 객체라고 가정한다고 말했습니다.

D3에서 추가를 살펴보겠습니다.

append("text").attr("class", "axis-label")

// attr assumes append is an object, not only an object, but one 
// that has a property attr, which is a function

// this is what attr assumes 

const append = {
    attr: function(arg1, arg2){

        // do some attr stuff
    }

}

append('text').attr()

// however if you observe carefully append is not an object, 
// but a function("text") taking a text arg ,
// so how is this possible, simple 
// append returns an object with the method attr 
// and that is what method chaining is: passing down an object //from method to method in the chain
// will make sense as we implement it




append는 attr 메서드가 있는 객체를 반환하고, attr은 attr 및 text 메서드가 있는 객체를 반환하는 식입니다.
그러나 "손"으로 전달된 개체의 모양을 정의할 필요는 없습니다. 그에 대한 OOP가 있습니다. this 키워드가 주변 컨텍스트를 참조한다는 것을 알고 있습니다. 개체this 내부에서 호출되면 객체, 우리는 객체에 많은 메서드를 가짐으로써 메서드 체인을 달성할 수 있습니다. 각 함수는 작업을 수행한 후 현재 객체를 참조하는 this 를 반환합니다.

const chainable = {

     one : function() {

     console.log("one")

     return this;    // this === chainable object

     }, 


     two: function () {

     console.log("two")

     return this



     },

     three: function() {

     console.log("three")

       return this;

     }





}




chainable.one()

.one()

.one()

.two()

.three()

.one()

// you can create a huge sequence as you can see above, each 
//method will return chainable
// to take it a step further you can even encode state in chainable and have it updated as you go along
// it's very easy



chainable의 각 메서드는 잘 반환됩니다: chainable 객체, 체인의 각 도트 연산은 이전 객체가 객체를 반환할 것으로 기대합니다. 예를 들어 액세스된 속성을 정의합니다.

chainable 
.one()  // expects chainable to have method one 
.two() // expects one() to have method two(), which does not but returns an object that does

// and so on




수업으로도 이것을 달성할 수 있습니다.


class Axis{


    append(text){
        // do something with text 
        console.log(text)
        return this; // current instance object 


    }

    attr(key, property){
      // do something 
      console.log(key, property)

      return this 

    }

    text(text){
     // do something 
     console.log(text)

     return this 

    }


}


const yAxis = new Axis()

yAxis
.append("hello world")
.attr("zIndex", 1)
.attr("backgroundColor", "black")
.text("hello again")
.text("good bye")
.attr("display", "flex")







그것으로 우리는 순차 프로그래밍을 달성하고 이전 것을 기반으로 작업을 수행합니다. 이것은 약속에 대한 좋은 Segue입니다. 이것이 약속이 무엇인지, 약속이라는 객체를 반환하는 메서드, 이러한 객체가 정의하고 포착하고 마지막으로 정의하기 때문입니다. 방법(익숙한 소리?)

다음으로 우리는 약속을 소개합니다

좋은 웹페이지 즐겨찾기