0

I tried to make inheritance, but I didn't expect that this.array will act like static member. How can I make it 'protected/public':

function A() {
    this.array = [];
}

function B() {
    this.array.push(1);
}
B.prototype.constructor=B;
B.prototype = new A();

Firebug:

>>> b = new B();
A { array=[1]}
>>> b = new B();
A { array=[2]}
>>> b = new B()
A { array=[3]}
4
  • Your last two lines are backwards, by the way. Set prototype.constructor after you set prototype. Commented Jan 26, 2012 at 2:33
  • I realize this is just an example, but why don't you do this.array = [1] instead? Commented Jan 26, 2012 at 2:35
  • Original code looks like: function Controller(uri) { this._controllerURI = uri; this._controllers = []; this._views = []; this._events = []; }. It's just a sample. Commented Jan 26, 2012 at 2:45
  • This question is similar to: How should the `.prototype` property be set up in a derived old-style constructor?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Dec 26, 2024 at 22:23

1 Answer 1

2

Not "private/protected", but this will make a new Array for each B.

function A() {
    this.array = [];
}

function B() {
    A.apply(this); // apply the A constructor to the new object
    this.array.push(1);
}
// B.prototype.constructor=B; // pointless
B.prototype = new A();
Sign up to request clarification or add additional context in comments.

2 Comments

I think you mean A.call(this);.
@user(\d)* Perfect. Thanks. @minitech: could be apply - it works. Where I can find docs/sample code for your $Query replacement?

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.