Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Javascript's native OOP is classless, what about the constructor? Doesn't that imply a class?

I think Javascript native OOP system is said to be classless, and is object-based, not class-based. But every example I see always start with a constructor similar to

function Person(name) {
    this.name = name;
}

Just by using a constructor this way, doesn't this already imply a class is being used? (a class called Person)


Details:

If we can use

a.__proto__ = b;

on any Javascript platform, then I think it is classless. But we can't do that. If we want that behavior, we need to use

function F() { }
F.prototype = b;
a = new F();

and so, a constructor has to be used. So if constructor is such a cornerstone in Javascript, that means it is intended to be constructor of Person, Widget, etc, and these are classes.

like image 527
nonopolarity Avatar asked Mar 01 '26 06:03

nonopolarity


1 Answers

The OOP in Javascript is slightly different from, for instance, the Java OOP. The Javascript constructors do not refer to a class definition (so it is classless). Rather the constructor refers to a prototype. The base of the OOP in Javascript is the Object object (not the Object class), from where all the others objects are derived.

Prototyping grants you inheritance, and the possibility to extend an existing object with properties and methods.

I suggest you this article.

In your example:

function Person(name) {
    this.name = name;
}

Mike = new Person('Mike');

the Person() function lets you create a new object prototyped on the Object object with a new property called name. Well, such a kind of function in Javascript oop is called a constructor.

like image 97
Alberto De Caro Avatar answered Mar 03 '26 20:03

Alberto De Caro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!