2

Let's suppose that I have the following object function:

function A(options){
 ...
}

Then I want to create a new function (B) that inherits A's prototype. These are the conditions I'm looking for:

  • B's prototype, if modified, should not modify A's
  • when calling to B function as a constructor, A's constructor should be called with the corresponding options.

B should look like this:

function B(aOptions, bOptions){ ... }

var b = new B({}, {})
Dan D.
  • 73,243
  • 15
  • 104
  • 123
Pato Loco
  • 1,205
  • 1
  • 13
  • 29
  • Javascript [doesn't have](http://www.crockford.com/javascript/inheritance.html) a classical inheritance mechanism. – amphetamachine Oct 10 '14 at 16:19
  • Answers to many JS questions can be found on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance – Felix Kling Oct 10 '14 at 16:53
  • There would be no need for 2 options. You can pass one and have the functions use or mutate whatever applies to that specific function. More on prototype and passing arguments to a chain of functions here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Oct 11 '14 at 00:27

1 Answers1

7

Just call A constructor with this

function B(aOptions, bOptions) {
  A.call(this, aOptions);

  // do stuff with bOptions here...
}

Now to setup the prototype

B.prototype = Object.create(A.prototype, {
  constructor: {
    value: B
  }
});

Now B will have the prototype methods from A.

Any new methods added to B's prototype will not be available to A's prototype


There's a couple other tweaks that can make your life easier too.

function A(options) {

  // make `new` optional
  if (!(this instanceof A)) {
    return new A(options);
  }

  // do stuff with options here...
}

And do the same for B

function B(aOptions, bOptions) {

  // make `new` optional
  if (!(this instanceof B)) {
    return new B(aOptions, bOptions);
  }

  // call parent constructor
  A.call(this, aOptions);

  // do stuff with bOptions here...
}

Now you can call A(options) or new A(options) to get the same result.

Same with B, B(aOptions, bOptions) or new B(aOptions, bOptions) will get the same result.

Mulan
  • 129,518
  • 31
  • 228
  • 259
  • so what will be the value of this in functon b ??..suppose if i call the function b with var a = new a() ..will that this point a or somewhat else ?? – Avinash Babu Oct 10 '14 at 16:25
  • @AvinashBabu all of the code here makes no modifications to A. `new A()` calls `A`, not `B`. The value of `this` will point to an instance of `B` when you call `new B()`. – Mulan Oct 10 '14 at 16:26
  • so if i call var b = new b() then the this points to the variable b right ?? – Avinash Babu Oct 10 '14 at 16:29
  • @AvinashBabu `var b = new B()` will give you a new instance of B, yep. – Mulan Oct 10 '14 at 16:33