-1

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

whoisit
  • 269
  • 3
  • 12
  • See also [JavaScript class property inside vs outside constructor](https://stackoverflow.com/q/64436532/5217142). You would explicitly declare a class constructor if you want to set individual instance properties to values passed to the constructor as arguments. I suggest taking care when combining technical jargon: "public instance" doesn't make sense that I know of. – traktor May 26 '23 at 09:12

1 Answers1

2

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.

ihoryam
  • 1,941
  • 2
  • 21
  • 24