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({}, {})
3
  • Javascript doesn't have a classical inheritance mechanism. Commented Oct 10, 2014 at 16:19
  • Answers to many JS questions can be found on MDN: developer.mozilla.org/en-US/docs/Web/JavaScript/… Commented Oct 10, 2014 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: stackoverflow.com/questions/16063394/… Commented Oct 11, 2014 at 0:27

1 Answer 1

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.

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

4 Comments

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 ??
@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().
so if i call var b = new b() then the this points to the variable b right ??
@AvinashBabu var b = new B() will give you a new instance of B, yep.

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.