Scope of .this on a constructor

class Vegetable {
constructor(name) {
this.name = name;
}
}

const carrot = new Vegetable(‘carrot’);
console.log(carrot.name);

my question: is contstructor an object or a function? and so, is -this- refering to the object Vegetable?

The constructor is a special type of function on classes. When someone instantiates a class using the new keyword, the constructor function is called.

new Vegetable('carrot')

This line creates a new object with the properties and methods defined in the Vegetable class, and runs its constructor with the argument 'carrot'. this refers to the object that is created.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.