Javascript Prototypes,objects,constructor??i am confused

前端 未结 4 1177
你的背包
你的背包 2020-12-18 11:28

I have gone through plenty of Stack Overflow question that had description but I seriously found them very confusing. What I want is a simple explanation,please don\'t refer

4条回答
  •  情深已故
    2020-12-18 12:12

    I guess I am too late, but here would be my 2 cents:

    Prototype:

    String.prototype.x = "yahoo"
    

    now every instance of String will have the property x.

    So be it (new String()).x or "".x both have the value equal to yahoo

    Hence it's like extending a predefined class.


    Objects

    Everything in JavaScript, except the other primitive types, is an object.

    An object is a collection of name-value pairs, nothing more, nothing less.

    {"a": 0, "b" : 1}
    

    Even an Array is an object in JS with some additional properties & methods.


    Functions & Methods

    Here is a function :

    function a() { };
    

    Now let's give it the status of a method of an Array:

    Array.prototype.a = a;
    

    Constructor:

    new String()
    

    gets the implementation of String from : String.constructor

    Similarly the code you write in any function goes into this very function.

提交回复
热议问题