Pseudo-classical inheritance

suggest change

It’s an emulation of classical inheritance using prototypal inheritance, which shows how prototypes work. It was written to look familiar to programmers coming from class-based languages.

IMPORTANT NOTE: Classes are the direct syntax for this pattern. Constructor functions still work. In an ES5 environment, the pseudo-classical pattern is the way to get the same prototype link.

A “class” here is a function meant to be called with the new operator. That call uses it as a constructor.

function Foo(id, name) {
    this.id = id;
    this.name = name;
}

const foo = new Foo(1, 'foo');
console.log(foo.id);

Console output

1

foo is an instance of Foo. By convention, a constructor’s name starts with a capital letter and is called with new.

To add properties or methods shared by those instances, add them to its prototype, the prototype property of the constructor.

Foo.prototype.bar = 'bar';
console.log(foo.bar);

Console output

bar

What Foo does as a constructor is create an object whose prototype is Foo.prototype.

You can find a reference to its constructor on every object

console.log(foo.constructor);

function Foo(id, name) { …

console.log({ }.constructor);

function Object() { [native code] }

And also check if an object is an instance of a given class with the instanceof operator

console.log(foo instanceof Foo);

true

console.log(foo instanceof Object);

true

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents