Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP In javascript

Im wondering which way of using OOP in Javascript ist best way to go with.

There is this prototype thing and you have the function style way. But both have very bad ways to inherit a base class.

So I tried to build a way to make this possible without having to use prototype and such.

function Car(name) {
    this.Name = name;

    this.FullName = function () {
        return this.Name;
    }
}

function SpecialCar(name, variant) {
    //BaseClass.apply(this, PARAMS AS ARRAY);
    Car.apply( this, [name] );

    //new property
    this.Variant = variant;

    //override function
    this.FullName = function () {
        return this.Name + " " + this.Variant ;
    }
}

var audi = new Car("audi");
$("#result").append(audi.FullName() + "<br>");

var audia3 = new SpecialCar("audi", "a3");
$("#result").append(audia3.FullName()+ "<br>");

You can check the jsFiddle here: http://jsfiddle.net/vu9ZF/2/

Is this okay or is it just bad-practice?

Would be very nice to get some answers why other ways are better because I just dont get it.

EDIT: Thank you all for answering me so fast! I was trying to find some way of OOP in javascript for myself, not answering on how to do oop in javascript. I dont like the way of using prototype for that because im using c# most of my worktime and its a bit confusing to switch between "c#-like oop" and "prototype oop". But someone in the comments told me that avoiding prototype isnt a good idea, soo ill drop that.

Thanks stackoverflow your all awesome & saved me so much time =)

like image 394
SSchnitzler Avatar asked Dec 12 '22 05:12

SSchnitzler


2 Answers

This is how it's done:

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

Car.prototype.fullName = function () {
    return this.name;
}

function SpecialCar ( name, variant ) {
    Car.apply( this, arguments );
    this.variant = variant;
}

SpecialCar.prototype = Object.create( Car.prototype );

SpecialCar.prototype.fullName = function () {
    return this.name + ' ' + this.variant;
}; 

(You need to shim Object.create for IE8)

Live demo: http://jsfiddle.net/3Rehr/


So, the methods should be assigned to the constructor's prototype object, not to the instances themselves.

Also, in order to pre-process the instance with the super-constructor, simply do this:

Car.apply( this, arguments );

so the this.base thing is not needed.

like image 102
Šime Vidas Avatar answered Dec 14 '22 18:12

Šime Vidas


It's not particularly recommandable because you actually return a Car instance and not a SpecialCar instance.

audia3 instanceof Car === true;
audia3 instanceof SpecialCar === false;

This is confusing because you do execute new SpecialCar. Also properties of SpecialCar.prototype wouldn't be available on the instance, but you seem to be using a custom inheritance copying pattern.

like image 33
pimvdb Avatar answered Dec 14 '22 18:12

pimvdb