Prototypes page
Demystify .prototype and ._proto_! We’ll cover what the "new" and "instanceof" operators are actually doing behind the scenes, and what prototype-based inheritance looks like in memory.
Overview
- Shared properties
- Methods/properties on a prototype
- Setting up the proto chain
- Object.create
- Exercise!
Video
Slides
Exercise 1: new Operator
The problem
Write the new
operator as if it was implemented in JS as a function. For example,
instead of calling new Person('name')
, we will call NEW(Person,['name'])
as follows:
NEW(constructor, args)
will take:
- constructor - a constructor function.
- args - an array of arguments.
To get started, click the button at the bottom of the following:
What you need to know
The new
operator does three things:
- Creates a new object.
- Assigns the object’s
__proto__
to the constructor function’sprototype
. - Calls the
constructorFn
constructor function with the object asthis
.
Other things to know:
- You can use Object.setPrototypeOf(obj, prototype) to set the
__proto__
property of an element. - Use apply to
call a function (also constructor functions) with a
this
value and an array of arguments.
The solution
Exercise 2: instanceof Operator
The problem
Write the instanceof operator as if it was implemented in JS. For example, instead of calling person instanceof Person
,
we will call it as INSTANCEOF(person, Person)
as follows:
To get started, click the button at the bottom of the following:
What you need to know
The instanceof operator returns true if the prototype property of a constructor appears anywhere in the prototype chain of an object.
A constructor function’s prototype is not an instance of the constructor function: