> For the complete documentation index, see [llms.txt](https://demirels-organization.gitbook.io/javascript-tutorial/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://demirels-organization.gitbook.io/javascript-tutorial/public-class-field.md).

# Public Class Field

In JavaScript, a "public class field" refers to a property or method that is directly attached to a class and can be accessed from any part of the program, both inside and outside the class. This is in contrast to a "private class field," which can only be accessed within the class itself. Public class fields are declared using the `constructor` method or directly in the class body, and can be accessed using the `this` keyword. For example:

```javascript
Copy codeclass MyClass {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    console.log(this.name);
  }
}

let myObject = new MyClass("John");
console.log(myObject.name); // "John"
myObject.sayName(); // "John"
```

In the example above, `name` and `sayName` are public class fields that can be accessed from anywhere.

It's worth noting that as of ECMAScript 2020 (ES11) version of javascript, it introduced a new syntax called `public class fields` which allows you to declare fields directly in the class body.

```typescript
Copy codeclass MyClass {
  publicName = "John";
  public sayName() {
    console.log(this.publicName);
  }
}

let myObject = new MyClass();
console.log(myObject.publicName); // "John"
myObject.sayName(); // "John"
```

It's also worth noting that this feature is not supported by all JavaScript engines and requires a transpilation step for older browsers.
