JavaScript 프로토타입 및 프로토타입 ⚙️

목차


  • Introduction
  • What is Proto?
  • Conclusion

  • 소개

    Javascript can be described as a prototype-based language. This stems from an object's ability to have a prototype object, which allows them to inherit features from one another. You can read more about this in the MDN Web Docs .

    그러나 콘솔에서 배열을 본 적이 있다면 __proto__를 알아차릴 수 있습니다. 정확히 무엇입니까?

    프로토 란 무엇입니까?

    If you don't already, open up your browser console. Now, create an empty array ([]). After you create the array, expand it using the > icon. Viola! You will see the **proto** attribute.

    []
    length: 0
    __proto__: Array(0) // <--- Here it is!
    length: 0
    constructor: ƒ Array()
    concat: ƒ concat()
    

    It does not matter how you create your array, you'll always find the proto attribute.

    let example = [1,2,3,4,5]
    
    example
    (5) [1, 2, 3, 4, 5]
    0: 1
    1: 2
    2: 3
    3: 4
    4: 5
    length: 5
    __proto__: Array(0) <-- woah! There it is again!
    

    Every time we construct a new array, it uses the Array constrcutor, so proto looks for an array blueprint. It references all properties and methods from that blueprint. If you type Array.prototype, you'll see same method list as the one above.

    Proto is Javascript's way to reference to the original prototype. And this applies to any react object!

    Let's try out another example...

    Object.prototype
    
    {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
    

    Boom! All the methods and properties.

    프로토타입에 추가



    믿거나 말거나 실제로 Array 청사진에 고유한 메서드를 추가할 수 있습니다.

    Array.prototype.phrase = () => console.log("I like math")
    


    이제 기존 배열에는 방금 생성한 예제 배열을 포함하여 이 구문 메서드가 있습니다.

    (5) [1, 2, 3, 4, 5]
    0: 1
    1: 2
    2: 3
    3: 4
    4: 5
    length: 5
    __proto__: Array(0)
    phrase: () => console.log("I like math") <--- Magic.
    


    구문 메서드를 호출하는 경우...

    example.phrase() // "I love math"
    


    결론

    1. Everything in javascript references methods/properties from its blueprint.
    2. You can add and modify prototype features in the blueprint.
    3. Proto references the original blueprint's prototype features.

    While there is more to dig into, this covers the basics of Javascript prototype and what it has to offer. Thanks for reading!

    좋은 웹페이지 즐겨찾기