Tell us what’s happening:
I have no trouble regarding the task. my confusion is around the purpose of class & new; what are they used for? i know that new in java creates a new object in memory & i know what a class is used for in java and python. but if it is not used for the same purpose (as mentioned in the lesson) then what is its usage? (i hope that i cleared the point enough)
Your code so far
// Only change code below this line
// var Vegetable = function(name){
// this.name = name;
// }
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 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36.
Challenge: Use class Syntax to Define a Constructor Function
I think you might be reading a little too much into this. Yes, classes in JS are not “full-fledged” implementations like in other object-oriented languages but they are still used for object-oriented programming in JS. I think the point the lesson was trying to make is that the added class syntax in JS is really just syntactic sugar and you can pretty much do object-oriented programming in JS without it. But for people who have experience with object-oriented programming in other languages, the new class syntax in JS makes a lot more sense.
The new operator existed before the new class syntax. It does the same thing it always has, creates a new instance of an object, or class, which is basically the same thing as an object.
It is used for the same purpose. It’s a class. Just because JS has a different form of OO that works slightly differently doesn’t mean you don’t use classes as classes
I just ran this with node and it threw the following error:
const carrot = Vegetable('carrot');
^
TypeError: Class constructor Vegetable cannot be invoked without 'new'
at Object.<anonymous> (/home/bbsmooth/test/test.js:7:16)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
There are a few differences between the new class syntax and the old ways of doing things. I believe that if you use the class syntax then you are required to use new when calling the constructor but you are not required to use new when doing it the old way. Consider this an improvement in the new class syntax as it will prevent you from making this error.