Initializing Fields in Order

At the start of this course, a JavaScript port of the drilling kit printed its label with the spaces still around it, even though Kit has a setter that trims every label. The setter was there, and it was correct. It never ran.

Every label the checkout desk prints relies on that validation. In this lesson, you’ll see why a class field skipped the setter, how to keep validation in the loop, and in which order JavaScript builds a subclass’s object. Start with the Python version that works.

Keep the Setter in the Loop

The Python module trims labels with a property. A preset for the drilling kit sets its default label in __init__(). To keep the focus on the label, this Kit holds only that property:

Language: Python
class Kit:
    @property
    def label(self):
        return self._label

    @label.setter
    def label(self, value):
        self._label = value.strip()

class DrillingKit(Kit):
    def __init__(self):
        super().__init__()
        self.label = "  drilling  "

The line self.label = " drilling " is an assignment, so Python finds the property on Kit and calls its setter. The instance’s own dictionary ends up holding only _label:

Language: Python
>>> kit = DrillingKit()
>>> kit.label
'drilling'
>>> vars(kit)
{'_label': 'drilling'}

In a JavaScript class, a class field is a name = value; line in the class body that gives every new instance its own starting value. Fields are where JavaScript classes usually put per-instance defaults, so a field looks like the tidy port of the label assignment in __init__():

Language: JavaScript
class Kit {
  get label() {
    return this._label;
  }

  set label(value) {
    this._label = value.trim();
  }
}

class DrillingKit extends Kit {
  label = "  drilling  ";
}

const kit = new DrillingKit();
console.log([kit.label, kit._label]);

The array shows quotes, so spaces stay visible. Does the setter trim the label? Predict both values, then run it.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.