Reputation: 679
Is there any reason why I should assign a new instance of one function-object to the prototype-attribute of another function-object? Would it represent some kind of inheritance mechanism?
function Foo() {}
function Bar() {}
new Bar() instanceof Bar; // true
new Bar() instanceof Foo; // false
// assign instance of Foo to Bar.prototype:
Bar.prototype = new Foo();
// that results in:
new Bar() instanceof Bar; // true
new Bar() instanceof Foo; // true
Upvotes: 2
Views: 43
Reputation: 138267
JavaScript has prototypal inheritance. Objects can inherit other objects. This basically means that you can "see" properties of the parent object¹ on the child:
const parent = { inherited: true };
const child = Object.create(parent);
child.inherited // true
Constructors are just functions, whose .prototype
property represents the object the instances inherit from:
const foo = new Foo();
// equals
const foo = Object.create(Foo.prototype);
Foo.call(foo); // execute the constructor with "this" being "foo"
Similarily instanceof
is also just a mechanism on the prototype chain: It checks wether the functions .prototype
is inside the objects parent chain.
Chain? Yes, objects whose parent also has a parent, also inherit the properties of the parents parent. So to create a "class" that inherits another "class", we have to set the classes .prototype
s parent to the superclasses .prototype
. That could be done with
Bar.prototype = new Foo();
because new Foo
returns an object whose parent is Foo.prototype
, therefore Bar instances inherit Bar.prototype
which inherits Foo.prototype
.
¹ The "parent object" is officially called "object prototype", I tried to avoid the possible confusion between the objects prototype and the function objects prototype property
Although this method works, you also execute the constructor of Foo
on something that is not really an instance (well technically yes, but not conceptually). There are (better) alternatives, e.g. creating instance without executing the constructor:
Bar.prototype = Object.create(Foo.prototype);
or directly setting the objects parent:
Object.setPrototypeOf(Bar.prototype, Foo.prototype);
Or, if you use class
syntax:
class Bar extends Foo {
//...
}
Upvotes: 3