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

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

2022-10-19 last update

6 minutes reading javascript beginners react devops

목차


  • 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!