user2217288
user2217288

Reputation: 547

javascript oop namespaces and inheritance

It create in name spaces object and I can use it.

Test = {};
Test.Car = function init(color){
    this.color = color;
}  
Test.Car.prototype.paint = function(color) {
    return this.color = color;
};
Test.Car.prototype.print = function(){
    return this.color;
}

Example of use:

var Car4 = new Test.Car('Blue');
Car4.paint('red');
alert(Car4.print());

Now I want to create new object and I want to inheritance form test:

Test2 = {} to do here to inheritance form Test and override using prototype ? Test2.prototype = Object.create(Test.prototype); not working

How can I do it. Need some help in that.

Upvotes: 0

Views: 55

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075209

Test is an object, not a "namespace" or a function, although sometimes people call objects that you put properties on namespaces (they aren't, really).

I'm not sure why you'd want to, but you can use Test as the prototype of Test2 by doing this:

var Test2 = Object.create(Test);

Now things like this work:

var c = new Test2.Car();

...because Test2 inherits Car from Test.

If you wanted to create a Car2, that's slightly more involved:

var Car2 = function() { // Or `Test.Car2 = function` or whatever
    Test.Car.apply(this, arguments);
    // Or: `Test.Car.call(this, "specific", "arguments", "here");`

    // ...Car2 stuff...
};
Car2.prototype = Object.create(Test.Car.prototype);
Car2.prototype.constructor = Car2;

Upvotes: 1

Related Questions