when we do something like this
const something = class extends anything {
}
What does it mean or what does it do? Does it store the value of class in a Variable? and how will this be different from
class something extends anything {
}
when we do something like this
const something = class extends anything {
}
What does it mean or what does it do? Does it store the value of class in a Variable? and how will this be different from
class something extends anything {
}
There is no such thing as a "class" in javascript in the same way that they exist in class-based languages like Java. In JS, the class syntax is sugar over the same old constructor function. When you understand that, your question becomes easier to reason with.
This:
const something = class extends anything {
}
Is (roughly) analogous to this:
const something = function() {
}
something.prototype = Object.create(anything.prototype)
And the same similarity goes for these variants:
class something extends anything {
}
function something() {
}
something.prototype = Object.create(anything.prototype)
Functions are first class objects in javascript, which means they can be treated as values and passed around. The difference between const something = class...
and class something...
is that the first is a class expression (assigning a class like a value to a variable that can be passed around) and the second is a class declaration (declaring the class and giving it a name, but not assigning it to a variable), but they are interchangeable in most scenarios.
For clarification, when you do something.prototype = Object.create(anything.prototype)
, this is the actual inheritance that Javascript uses. It roughly means that you take the "prototype" of a constructor function and use it as a base for the next one, and that means that whatever object that you create using new something()
will have the prototype of anything
, plus any other attributes that you need to add to something.prototype
.
You can get more in-depth info here: Inheritance and the prototype chain and Prototypal Inheritance in JavaScript
Just to note that declaring const something = code
means in practice that all of the following is impossible:
function something(){//code}
var something;
let something;
class something{
//whatever
}
That specific name is reserved, the purpose of const
is that, otherwise, you could rewrite the class itself using the same name like this:
var something = class anything {//code
}
var something = class anything {//code changes previous class
}
And again, this is not possible:
class anything {//code
}
class anything {//code changes previous class
}
You can't change anything. So I think there is no practical difference between const something = class
and class something extends anything
because both are names reserved and "versions" of other classes.