Tell us what’s happening:
Could someone explain to me an idea of Construction Function?
**Your code so far**
// Only change code below this line
class Vegetable {
constructor(name) {
this.name = name;
}
}
// Only change code above this line
const carrot = new Vegetable('carrot');
console.log(carrot.name); // Should display 'carrot'
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
Challenge: Use class Syntax to Define a Constructor Function
When you want to create an instance of new type of object, in this case Vegetable, you use a function and you call it with the keyword new in front of it. When you use new, and properties in the function body that are preceded with this are added as properties of the new type of object.
new Vegetable("carrot")
which produces an object:
{ name: "carrot" }
It works fine without using class syntax, it’s literally just a function (it’s the new that does the magic object creation):
function Vegetable (name) {
this.name = name;
}
const carrot = new Vegetable("carrot");
// { name: "carrot" }
class syntax just wraps everything up so that it’s consistent, and prevents the common error of a programmer forgetting new – what I mean is:
I understand that Construction Function (that uses special syntax of class ) creates a new object inside of variable(carrot), that object has a property name: "carrot" ?
notice, its “constructor”, not “construction” function. It refers to the special constructor function within the class body, which purpose is to define variables(keys/properties) for the constructed object.
The example creates an object named “carrot” and assigns to it a key with name “name”, to which it assigns a value “carrot”. The regular way of creating similar object would look like this:
const carrot={
name: 'carrot'
}
Constructor functions and class syntax are good way to create multiple objects, which share same construction. Its especially convenient, when you need to work with multiple objects which have complicated built and it just looks ugly(and takes time) when you need to write all that in the start of your program.