0

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.

4
  • Test is the namespace and car is your object. did you meant you wanted to inherit from the Car object Commented Feb 26, 2015 at 10:26
  • Test isn't a namespace, it's just an object. Object.create(Test.prototype) doesn't work because Test isn't a function. What is it you want to "inherit" from Test? Commented Feb 26, 2015 at 10:26
  • @T.J.Crowder: correct, I meant the OP is trying to assume the Test object as his namespace or in other words the container Commented Feb 26, 2015 at 10:28
  • @unikorn: Actually I was talking to the OP. Commented Feb 26, 2015 at 10:29

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

That was key var Test2 = Object.create(Test);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.