1

I want to know if it's possible having something like this:

  • basic class A
  • derived class B1 from one instance a of class A (i.e. a = new A() )
  • derived class B2 from same instance a of A

I give an example:

var a = new A();
function A() {
    this.var_test = 0;
    this.test = function () {
        alert(this.var_test++);
    }
}

function B1() {
}
B1.prototype = a;

function B2() {         
}
B2.prototype = a;

var b1 = new B1();
var b2 = new B2();
b1.test(); // i want alert(0)
b2.test(); // i want alert(1)

How to do it?

2 Answers 2

1

Sure, just use the standard methods for inheritance:

console.clear();
function A() {
  this.test = function() {
    alert(A.var_test++);
  }
  A.var_test = 0;
}
var a = new A();
b1 = Object.create(a);
b2 = Object.create(a);
b1.test();
b2.test();
b1.test();
b2.test();

Sign up to request clarification or add additional context in comments.

1 Comment

yeeeah, that's what i need! thank you for your example
0

Here’s some recommended reading from Douglas Crockford on classical inheritance in JavaScript: http://javascript.crockford.com/inheritance.html

As he says, quite succinctly:

JavaScript is a class-free, object-oriented language, and as such, it uses prototypal inheritance instead of classical inheritance. This can be puzzling to programmers trained in conventional object-oriented languages like C++ and Java. JavaScript's prototypal inheritance has more expressive power than classical inheritance […]

Comments

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.