skip to Main Content

we know that classes are just functions in javascript and classes is just an abstraction, syntactic sugar, whatever you want to call it, over its prototype-based inheritance. For example:

class foo {
  bar() {}
}

is transformed to:

function foo() {}
foo.prototype.bar = function() {};

but if we use a public instance as

class foo {
  bar = "Hello World";
}

we cannot access the bar instance properies as
foo.prototype.bar (undefined)

I know we have to create a new instance to access it like:

var instance = new foo();
console.log(instance.bar);  // "Hello World"

but somehomw bar property must be baked in foo‘s proptotye, so where is it?

learn how pubilc instance is used internally by ES6

2

Answers


  1. These fields are not placed on the prototype. Instead, they are directly attached to each instance of the class

    With the field declaration bar = "Hello World"; inside your foo class, when you create an instance of foo, JavaScript automatically assigns bar to that instance within its constructor. So it is equivalent to this

    class foo {
      constructor() {
        this.bar = "Hello World";
      }
    }
    

    That’s why you cannot access bar through foo.prototype.bar as it’s not part of the prototype. It is an instance variable that is unique to each object instantiated from the class.

    The bar property isn’t "baked" into foo’s prototype. It is directly attached to each object instantiated from the foo class.

    Login or Signup to reply.
  2. The instance of the class is simply a JS object. An interesting thing is that instance.rebar does not get logged in the following example when logging the instance while you can still access it through instance.rebar

    // A classic object
    const obj = {bar: "Hello world"};
    console.log("Classic obj", obj);
    console.log(typeof obj); // Object
    
    
    // A JS class
    class Test {
      bar = "Hello world";
      rebar() {}
    }
    
    const instance = new Test();
    console.log("JS class", instance);
    console.log(typeof instance); // Object
    
    console.log("Keys of instance", Object.keys(instance)); // bar
    
    // Instance.rebar
    console.log("Class method rebar", instance.rebar); // Defined but not logged
    
    // Instance prototype
    console.log("Class prototype", instance.prototype); // Undefined
       
    // Function
    function test() { const a = "Hello world"; }
    console.log("Function prototype", test.prototype);

    To keep it short: The class instance is not a function

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search