JavaScript의 구조 함수에 대한 간단한 설명서

카탈로그

  • An Introduction To Constructors
  • Functions, Constructors And The new Operator
  • Constructors And Prototypal Inheritance
  • JavaScript's Built-In Constructors
  • Closing Thoughts
  • 1. 시공자 안내

    In the previous article in this series, we looked at prototypal inheritance in JavaScript and talked about important object-oriented (OOP) JavaScript concepts like the prototype, the prototype chain, inheritance, and more. We also looked at how to set an object's prototype using its __proto__ property (we noted that this is not the recommended way.) and dealt with the this variable in detail.
    You can read through this article below:



    본고에서, 우리는 추천된 자바스크립트로 대상의 원형을 설정하는 방법을 보면서 우리의 토론을 계속할 것이다.
    비록 몇 가지 방법이 이 점을 할 수 있지만, 우리가 여기서 중점을 두는 것은 함수 구조 함수다.

    We will deal with the other recommended methods in the upcoming articles in this series. Talking in detail about all of them; in a single article would make it very long and grueling to read!



    시공자
    JavaScript의 구조 함수는 객체를 구성하는 데 사용되는 특수 함수입니다.이 화제는 보기에는 매우 어렵고 무섭지만, 실제로는 매우 간단하다.

    💡 The key to understanding constructors is to know that they are actually normal JavaScript functions. What makes them special is that they are always invoked along with a very powerful operator in JavaScript called the new operator.


    다음 코드를 실행하고 결과를 고려해 주십시오.
    기능 인원() {
    이것firstname="로렌스"
    이것lastname="매"
    이것직업 = "소프트웨어 개발자"
    이것성별 = "남성"
    }
    const Lawrence = 신인();
    위로하다log(로렌스);
    위의 작은 예시에서 새로운 대상을 만들고 그것에 대한 인용을 로렌스 변수에 저장합니다.이 객체에는 Person 구조 함수에 지정된 모든 속성이 있습니다.
    Person 함수 자체는 일반적인 JavaScript 함수이다.이 행 코드는 함수를 구성하는 능력(객체를 구성하는 능력)을 부여합니다.
    const Lawrence = new Person();  
    

    ✨ The new operator modifies the behaviour of the function it operates on. Using this along with some JavaScript design patterns, we are able to create powerful constructors. We will elaborate on this in the next section.


    2. 함수, 구조 함수와 새 조작부호

    In section 1 we learned that when the Person constructor, (or any other constructor) is invoked without the new operator it is invoked as a regular JavaScript function. In this section, we will elaborate on this with code examples.
    Kindly consider the code below.

    function Person () {
         this.firstname = "Lawrence"
         this.lastname = "Eagles"
         this.occupation = "Software Developer"
         this.gender = "male"
    }
    

    Above is the declaration of the Person function. We can notice two things from it viz:

    • It sets some properties e.g firstname, lastname, occupation, and gender to the object the this variable binds (or is pointing) to. In this case the global object.

    💡 As mentioned in the previous article in this series, one rule of the this variable is that when it is used inside a function it points to the global object but when it is used inside a method (a function in an object) it would point to that object

    If this is not very clear to you, feel free to visit my previous article on OOP JavaScript. I have already provided a link to it in section 1.
    However, here is a quick recap.
    Kindly run the code below and consider its result

    const devName = "Lawrence Eagles" function tellDevName () { console.log("result", this.devName) } tellDevName(); // returns "Lawrence Eagles"

    The above example shows that the this variable inside a function is pointing to the global object.

    • Another thing that should be pretty obvious about the Person function is that it does not have a return statement hence when invoked it would return undefined.

    💡 The JavaScript engine would return undefined from any function that does not return a value. This behaviour is leveraged in creating constructors as we are able to modify what that function returns using the new operator. Hence it is a common pattern in JavaScript, that constructors do not have a return statement


    신규 사업자
    이것은 함수의 일부 동작을 수정할 수 있는 매우 강력한 JavaScript 조작부호입니다.
    처음에는 새로운 조작원이 매우 곤혹스러울 수도 있고, 심지어는 좀 무섭기도 하다.

    The key to understanding it is to always see it as another regular JavaScript operator. Hence, a good understanding of operators in JavaScript is necessary to grasp the power of this operator.



    조작원
    연산자는 구문에서 일반 함수와 다른 특수한 JavaScript 함수입니다.일반 JavaScript 함수 객체가 아니므로 콘솔에 전달됩니다.dir () 는 오류를 일으킬 수 있습니다.아래에서 코드 예시를 볼 수 있습니다.
    다음 코드를 실행하고 결과를 고려하십시오.
    함수 tellDevName() {
    위로하다로그("결과", this.devName)
    }
    위로하다dir("함수 속성", tellDevName)
    위로하다dir("함수 속성", 날짜)
    //아래 줄에 대한 설명을 취소하고 실행 중인 코드를 실행하면 오류가 발생합니다.
    //콘솔.dir("함수 속성", +)
    //콘솔.dir("함수 속성", 신규)

    💡 The console.dir() displays an interactive list of the properties of the specified JavaScript object



    코드를 실행할 때tellDevName 함수와 날짜 구조 함수의 모든 속성을 볼 수 있지만, 매개 변수로 연산자를 전달하는 줄에 대한 설명을 취소하고 코드를 실행하려고 시도하면runkit는 일반적인 함수 대상이 아니라는 오류를 던집니다.
    정규 함수와 매우 비슷한 것은 연산자는 매개 변수(조작수라고 부른다)를 받아들이지만, 정규 함수와 달리 다음과 같은 세 가지 기호 중 어느 형태로든 사용할 수 있는 편리한 문법을 제공한다.
  • 접두사 표현법: 이 표현법에서 연산자는 그 조작수 사이에 놓인다.
    다음 코드를 고려하십시오.
  • 2 + 2 // returns 4
    3 * 3 // returns 9
    4 - 4 // returns 0
    5 / 5 // returns 1
    6 % 2 // returns 0
    
    위의 예시에서 모든 연산자는 두 개의 매개 변수 (조작수) 사이에 있고 값을 되돌려줍니다.Learn more about the infix notation here
  • 접두사 표현: 이 표현법에서 연산자는 그 조작수를 따른다.
    다음 코드를 고려하십시오.
  • const mixNumbers = [1,2,3,4,5,6,7,8,9,10,11,12]
    const evenNumbers = []
    for (let i=0; i < mixNumbers.length; i++) {
        if (mixNumbers[i] % 2 === 0){
           evenNumbers.push(mixNumbers[i])
        }
    }
    console.log("even numbers", evenNumbers)
    
    위에는 숫자 목록에서 짝수를 찾는 작은 예시가 있다.그러나 이 예에서 우리가 관심을 가지는 것은 증량 연산자이다.
    감량 연산자도 있다.Learn more about the postfix notation
    다음 코드를 고려하십시오.
    i++ increment operator
    i-- decrement operator
    
  • 접두사 표현: 이 표현에서 연산자는 그 조작수 앞에 있다.Learn more about the prefix notation
    다음 코드를 고려하십시오.
  • !true               // logical NOT (!) returns false
    !false              // logical NOT (!) returns true
    ++i                 // prefix increment             
    --i                 // prefix decrement
    new constructor()   // returns the newly constructed object
    
    위의 예시에서 우리는 새로운 조작부호가 접두사 표현법을 사용하여 함수 (구조 함수) 를 호출하고 새로운 구조의 대상을 되돌려주는 것을 볼 수 있다.

    🎉 I do hope that our succinct discourse on operators, would make you understand the new operator better and hence further your understanding of function constructors


    연산자에 대한 이해를 통해 우리는 새로운 운산자가 실제로 함수(구조 함수)를 매개 변수(조작수)로 호출한 다음에 그에 대해 조작을 하고 값을 되돌려주는 것을 똑똑히 볼 수 있다.
    다음은 새로운 운산자가 함수 구조 함수에 대한 조작이다.
  • 빈 대상을 만들고 이 변수를 새로 만든 대상에 연결합니다.
  • 함수가 자신의 대상을 되돌려주지 않으면 이 변수가 귀속된 대상 (새로 만든 대상) 을 되돌려줍니다. 이것이 바로 구조 함수가 되돌아오는 문장이 없어야 하는 이유입니다.
    다음 코드를 실행하고 결과를 고려하십시오.
  • //정규 함수
    함수자 () {}
    const regularDeveloper = 개인()
    위로하다로그(일반 함수 결과,regularDeveloper)
    //건조사
    기능 인원() {
    위로하다로그 ("this binds to", this)
    }
    const constructorDeveloper=new Person()
    위로하다로그("개인 구조 함수 결과", constructorDeveloper)
    기능 나쁜 사람 () {
    위로하다로그 ("this binds to", this)
    return{name:“Jack”,age:“70”}
    }
    const BadJack = 새로운 나쁜 사람()
    위로하다로그("나쁜 사람 구조 함수 결과", BadJack)
    위의 코드 예시에서 나는 이 세 함수 중 두 개에 같은 이름을 부여했지만, 자바스크립트는 대소문자를 구분하기 때문에 두 개의 다른 함수이다.구조 함수 이름의 첫 번째 자모는 대문자이고 일반적인 함수 이름은 소문자이므로 주의하십시오.

    💡 We use this pattern in JavaScript to differentiate constructors from regular functions. The first letter of a constructor's name is always capitalized. This would also serve as a reminder for you to use the new operator with every constructor. In our code example above, Person is the constructor and person is the regular function.


    위 코드의 결과를 보면 정규 함수는 정의되지 않은 것을 예상대로 되돌려주지만, 구조 함수는 새로운 연산자가 만든 새로운 대상을 되돌려줍니다. 이 연산자는 이 구조 함수 중의this 변수를 이 대상에 연결합니다.

    💥 Also notice the BadPerson constructor that returns its own object fails to return the object created from the new operator. This is a pitiful we must avoid. Again, as a rule, a constructor should not have a return statement❗




    구조 함수 작성을 위한 JavaScript 설계 모드
    구조 함수와 새로운 산자에 대한 이해를 통해 우리는 새로운 구조의 대상에 쉽게 속성을 추가할 수 있다.이것은 일반적인 JavaScript 모드입니다.
    다음 코드를 고려해 주십시오
    function Person () {
         this.firstname = "Lawrence"
         this.lastname = "Eagles"
         this.occupation = "Software Developer"
         this.gender = "male"
    }
    
    여기서 유일한 제한은 이 구조 함수로 만들어진 모든 대상이 항상 이런 속성을 가지고 있다는 것이다.다른 한편, 대상의 속성을 동태화하기 위해 우리는 그것들을 매개 변수로 구조 함수에 전달할 수 있다. (구조 함수는 우선 정규 함수이기 때문이다.)
    다음 코드를 실행하고 결과를 고려하십시오.
    기능자 (이름, 성, 직업, 성별) {
    이것이름
    이것성씨
    이것직업
    이것성별
    }
    const Developer = 신인("Lawrence", "Eagles", "Software Developer", "Male")
    const Doctor=신인("벤", "캐슨", "신경외과 의사", "남자")
    const Scientist=신인("Albert", "Einstein", "Scientist", "Male")
    위로하다로그("개발자", 개발자)
    위로하다일지 ("의사", 의사)
    위로하다일지("과학자", 과학자)
    상기 코드의 운행 결과에서 우리는 새로운 운산자를 사용하여 호출할 때 모든 구조 함수에 전달되는 매개 변수가 새로운 구조 대상의 속성을 설정하는 데 사용되는 것을 볼 수 있다.
    You can read more about the new operator at MDN .
  • 마지막으로 새 조작부호는 새로 만든 대상의 원형 링크(설정)를 다른 대상에 연결합니다.
    우리의 소개에서 우리는 설정 대상의 원형을 추천하는 방법을 토론할 것이라고 말했는데, 우리의 중점은 함수 구조 함수이다.이 점은 우리의 장편 논술을 주제로 되돌릴 것이다.우리는 다음 절에서 그것을 더욱 토론합시다.
  • 3. 구조기와 원형 계승

    In JavaScript, every function has a property called the prototype. This sits as an empty object in the function and remains dormant throughout the life of that function. It would only become active and quite useful if that function is used as a constructor.

    💡 The prototype property of a function (which is an object in JavaScript) is not the prototype of that function object but it acts as the prototype of any object constructed with that function when it is used as a constructor. The naming is a little confusing but we love our JavaScript 😉

    Kindly run the code below and consider its result:

    function Person (firstname, lastname, occupation, gender) { this.firstname = firstname this.lastname = lastname this.occupation = occupation this.gender = gender } // lets add some properties to the prototype property of the Person constructor. Person.prototype.getPersonBio = function () { console.log("Hello my name is " + this.lastname + " " + this.firstname + " I am a " + this.occupation ) } const Developer = new Person("Lawrence", "Eagles", "Software Developer", "Male") const Doctor = new Person("Ben", "Carson", "Neurosurgeon", "Male") const Scientist = new Person("Albert", "Einstein", "Scientist", "Male") console.log("Developer's bio:", Developer.getPersonBio()) console.log("Doctor's bio:", Doctor.getPersonBio()) console.log("Scientist's bio", Scientist.getPersonBio())

    From the results of the code above we can see that all the objects constructed with the Person constructor have access to the getPersonbio method which sits in the prototype property of the Person constructor. As we have noted above this property becomes the prototype of each object.

    The details of how the search is made down the prototype chain in other for all the constructed object to access the getPersonBio method has already been discussed in the previous article. I would kindly suggest you take a look at it if this section is not very clear to you.

    4. JavaScript의 내장 구조 함수

    JavaScript comes with some built-in constructors. If you are a JavaScript developer, there is a high probability that you have used some of them.
    Kindly run the code below and consider its result:

    const NumObject = new Number("20") const StringObject = new String("Hello World") const Today = new Date() console.log(NumObject) console.log(StringObject) console.log(Today)
    From running the codes above we can see that each returns an object because every constructor in JavaScript returns an object.
    You can learn more about each of these built-in constructors from the links below:
    Number Constructor
    String Constructor
    Date Constructor

    These are just a selected few you can get a more robots list here


    5. 끝말

    I do hope you followed through to this point. If you did you are really appreciated. It has been a long discussion, and I hope you got a thing or two. If so, I would now be looking forward to hearing your opinions, comments, questions, or requests (in case anything is not clear) in the comments section below.

    좋은 웹페이지 즐겨찾기