|
|
|
|
|
by azangru
3034 days ago
|
|
> I know it can be confusing for people coming from an OOP language, but in Javascript an object IS NOT an instance of a class. I’ve worked with C++ for about ten years, so I understand it feels right when doing > let mine = new MyClass(); > you get an ‘object’. But when thinking that you forget that Javascript is not a ‘class based’ language, it uses a prototypal approach. I really wish he were more specific about this. When in Javascript we write: function Foo() {
this.x = 'something';
}
foo = new Foo();
foo instanceof Foo; // true
foo.constructor === Foo; // true
the language tells us that the object `foo` is indeed an "instance" created by the constructor function `Foo`. What is the essential difference between this and what we have in object-oriented languages? What are the practical implications of Javascript being "not a ‘class based’ language" that "uses a prototypal approach"? |
|
Strictly speaking, there is no essential difference because it's entirely possible to implement classical inheritance using prototypal inheritance -- just not the other way around.
There's no classical equivalent of this, for example:
Note how bar has no "hello" property, so the property is looked up on its prototype, foo.Your code uses the "new" keyword. That keyword is pretty much emulating classical behaviour on top of the prototypal inheritance. The following two examples are equivalent:
and Every function implicitly has a "prototype" property which is set to an object with a "constructor" property set to the function itself.Object.create creates a new object and sets its prototype (the internal [[Prototype]] property, not the "prototype" property on the function) to its argument.
There's a bit more going on underneath (mostly to allow certain optimisations) but conceptually even the "new" keyword is just syntactic sugar.