Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: passing constructor arguments down the prototype chain. Is there a way?

Tags:

javascript

In the following example, is there a way to construct the object such that “b” has a property a1, initialised to “2”?

function A(a1) {
    this.a1 = a1;
}

function B(b1, a1) {
    this.b1 = b1;
}

B.prototype = new A;

var b = new B('1', '2');

I am basically trying to duplicate what would be known as “calling the base constructor” in a traditional object orientated language (such as c#).

like image 216
zod Avatar asked Sep 24 '10 15:09

zod


People also ask

What is the biggest advantage of prototypal inheritance in JavaScript?

Hence prototypal inheritance is just as powerful as classical inheritance. In fact it's much more powerful than classical inheritance because in prototypal inheritance you can hand pick which properties to copy and which properties to omit from different prototypes.

Is __ proto __ deprecated?

__proto__ Deprecated: This feature is no longer recommended.

How does prototypal inheritance work in JavaScript?

The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the [[Prototype]] of an object, we use Object. getPrototypeOf and Object.

What is the difference between __ proto __ vs prototype?

The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.


1 Answers

Like this?

function B(b1, a1) {
    A.call(this, a1);
    this.b1 = b1;
}
like image 107
npup Avatar answered Oct 30 '22 22:10

npup