Objects play a crucial role in JavaScript, serving as a fundamental element in nearly every facet of the programming language. When you began your journey in JavaScript, one of the initial topics you likely explored was the creation of objects. To delve into the intricacies of prototypes in JavaScript, it's beneficial to revisit the basics through the perspective of a junior developer.
Objects in JavaScript are essentially collections of key/value pairs. The primary method of creating an object involves using curly braces {}. Properties and methods are then added to the object using dot notation.
let animal = {}
animal.name = 'Leo'
animal.energy = 10
animal.eat = function (amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
animal.sleep = function (length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
animal.play = function (length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
Basic. In our program, it's likely that we'll have to generate multiple animals. To streamline this process, we should organize the logic into a function that we can use whenever we want to make a new animal. This approach is known as Functional Instantiation, and the function is referred to as a "constructor function" because it constructs a new object.
Functional Instantiation
function Animal (name, energy) {
let animal = {}
animal.name = name
animal.energy = energy
animal.eat = function (amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
animal.sleep = function (length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
animal.play = function (length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
return animal
}
const leo = Animal('Leo', 7)
const snoop = Animal('Snoop', 10)
"I thought this was an Advanced JavaScript course...?" - Your brain
It is. We'll get there.
Now, when we wish to generate a new animal or instance, we simply invoke our Animal function and provide it with the animal's name and energy level. This approach is efficient and straightforward. However, there is a notable drawback to this pattern. The issue lies with the three methods - eat, sleep, and play. These methods are not only dynamic but also entirely generic. This implies that recreating these methods for each new animal is unnecessary and results in wasted memory, making each animal object larger than necessary. Is there a solution to this problem? What if, instead of repeatedly creating these methods for every new animal, we transfer them to their own object, allowing each animal to reference that shared object? This approach can be termed as Functional Instantiation with Shared Methods, although it may sound verbose, it accurately describes the concept.
Functional Instantiation with Shared Methods
const animalMethods = {
eat(amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
},
sleep(length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
},
play(length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
}
function Animal (name, energy) {
let animal = {}
animal.name = name
animal.energy = energy
animal.eat = animalMethods.eat
animal.sleep = animalMethods.sleep
animal.play = animalMethods.play
return animal
}
const leo = Animal('Leo', 7)
const snoop = Animal('Snoop', 10)
By moving the shared methods to their own object and referencing that object inside of our Animal
function, we've now solved the problem of memory waste and overly large animal objects.
Object.create
Let's enhance our example further by employing Object.create. In simple terms, Object.create enables the creation of an object that delegates failed property lookups to another object. To put it another way, when a property lookup on the created object fails, Object.create allows it to check another object to see if that object contains the desired property. To make it clearer, let's take a look at some code.
const parent = {
name: 'Stacey',
age: 35,
heritage: 'Irish'
}
const child = Object.create(parent)
child.name = 'Ryan'
child.age = 7
console.log(child.name) // Ryan
console.log(child.age) // 7
console.log(child.heritage) // Irish
So in the example above, because child
was created with Object.create(parent)
, whenever there's a failed property lookup on child
, JavaScript will delegate that lookup to the parent
object. What that means is that even though child
doesn't have a heritage
property, parent
does so when you log child.heritage
you'll get the parent
's heritage which was Irish
.
Now with Object.create
in our tool shed, how can we use it in order to simplify our Animal
code from earlier? Well, instead of adding all the shared methods to
the animal one by one like we're doing now, we can use Object.create to
delegate to the animalMethods
object instead. To sound really smart, let's call this one Functional Instantiation with Shared Methods and Object.create
?
Functional Instantiation with Shared Methods and Object.create
const animalMethods = {
eat(amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
},
sleep(length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
},
play(length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
}
function Animal (name, energy) {
let animal = Object.create(animalMethods)
animal.name = name
animal.energy = energy
return animal
}
const leo = Animal('Leo', 7)
const snoop = Animal('Snoop', 10)
leo.eat(10)
snoop.play(5)
? So now when we call leo.eat
, JavaScript will look for the eat
method on the leo
object. That lookup will fail, then, because of Object.create, it'll delegate to the animalMethods
object which is where it'll find eat
.
So
far, so good. There are still some improvements we can make though. It
seems just a tad "hacky" to have to manage a separate object (animalMethods
)
in order to share methods across instances. That seems like a common
feature that you'd want to be implemented into the language itself.
Turns out it is and it's the whole reason you're here - prototype
.
So what exactly is prototype
in JavaScript? Well, simply put, every function in JavaScript has a prototype
property that references an object. Anticlimactic, right? Test it out for yourself.
function doThing () {}
console.log(doThing.prototype) // {}
What if instead of creating a separate object to manage our methods (like we're doing with animalMethods
), we just put each of those methods on the Animal
function's prototype? Then all we would have to do is instead of using Object.create to delegate to animalMethods
, we could use it to delegate to Animal.prototype
. We'll call this pattern Prototypal Instantiation
.
Prototypal Instantiation
function Animal (name, energy) {
let animal = Object.create(Animal.prototype)
animal.name = name
animal.energy = energy
return animal
}
Animal.prototype.eat = function (amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
Animal.prototype.sleep = function (length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
Animal.prototype.play = function (length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
const leo = Animal('Leo', 7)
const snoop = Animal('Snoop', 10)
leo.eat(10)
snoop.play(5)
??? Hopefully you just had a big "aha" moment. Again, prototype
is just a property that every function in JavaScript has and, as we saw
above, it allows us to share methods across all instances of a
function. All our functionality is still the same but now instead of
having to manage a separate object for all the methods, we can just use
another object that comes built into the Animal
function itself, Animal.prototype
.
Let's. Go. Deeper.
At this point we know three things:
- How to create a constructor function.
- How to add methods to the constructor function's prototype.
- How to use Object.create to delegate failed lookups to the function's prototype.
Those
three tasks seem pretty foundational to any programming language. Is
JavaScript really that bad that there's no easier, "built in" way to
accomplish the same thing? As you can probably guess at this point there
is, and it's by using the new
keyword.
What's nice about the slow, methodical approach we took to get here is you'll now have a deep understanding of exactly what the new
keyword in JavaScript is doing under the hood.
Looking back at our Animal
constructor, the two most important parts were creating the object and returning it. Without creating the object with Object.create
, we wouldn't be able to delegate to the function's prototype on failed lookups. Without the return
statement, we wouldn't ever get back the created object.
function Animal (name, energy) {
let animal = Object.create(Animal.prototype)
animal.name = name
animal.energy = energy
return animal
}
Here's the cool thing about new
- when you invoke a function using the new
keyword, those two lines are done for you implicitly ("under the hood") and the object that is created is called this
.
Using comments to show what happens under the hood and assuming the Animal
constructor is called with the new
keyword, it can be re-written as this.
function Animal (name, energy) {
// const this = Object.create(Animal.prototype)
this.name = name
this.energy = energy
// return this
}
const leo = new Animal('Leo', 7)
const snoop = new Animal('Snoop', 10)
and without the "under the hood" comments
function Animal (name, energy) {
this.name = name
this.energy = energy
}
Animal.prototype.eat = function (amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
Animal.prototype.sleep = function (length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
Animal.prototype.play = function (length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
const leo = new Animal('Leo', 7)
const snoop = new Animal('Snoop', 10)
Again the reason this works and that the this
object is created for us is because we called the constructor function with the new
keyword. If you leave off new
when you invoke the function, that this
object never gets created nor does it get implicitly returned. We can see the issue with this in the example below.
function Animal (name, energy) {
this.name = name
this.energy = energy
}
const leo = Animal('Leo', 7)
console.log(leo) // undefined
The name for this pattern is Pseudoclassical Instantiation
.
If JavaScript isn't your first programming language, you might be getting a little restless.
"WTF this dude just re-created a crappier version of a Class" - You
For those unfamiliar, a Class allows you to create a blueprint for an object. Then whenever you create an instance of that Class, you get an object with the properties and methods defined in the blueprint.
Sound familiar? That's basically what we did with our Animal
constructor function above. However, instead of using the class
keyword, we just used a regular old JavaScript function to re-create
the same functionality. Granted, it took a little extra work as well as
some knowledge about what happens "under the hood" of JavaScript but the
results are the same.
Here's the good news. JavaScript isn't a dead language. It's constantly being improved and added to by the TC-39 committee.
What that means is that even though the initial version of JavaScript
didn't support classes, there's no reason they can't be added to the
official specification. In fact, that's exactly what the TC-39 committee
did. In 2015, EcmaScript (the official JavaScript specification) 6 was
released with support for Classes and the class
keyword. Let's see how our Animal
constructor function above would look like with the new class syntax.
class Animal {
constructor(name, energy) {
this.name = name
this.energy = energy
}
eat(amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
sleep(length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
play(length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
}
const leo = new Animal('Leo', 7)
const snoop = new Animal('Snoop', 10)
Pretty clean, right?
So if this is the new way to
create classes, why did we spend so much time going over the old way?
The reason for that is because the new way (with the class
keyword) is primarily just "syntactical sugar" over the existing way we've called the pseudoclassical pattern. In order to fully understand the convenience syntax of ES6 classes, you first must understand the pseudoclassical pattern.
At this point we've covered the fundamentals of JavaScript's prototype. The rest of this post will be dedicated to understanding other "good to know" topics related to it. In another post we'll look at how we can take these fundamentals and use them to understand how inheritance works in JavaScript.
Array Methods
We
talked in depth above about how if you want to share methods across
instances of a class, you should stick those methods on the class' (or
function's) prototype. We can see this same pattern demonstrated if we
look at the Array
class. Historically you've probably created your arrays like this
const friends = []
Turns out that's just sugar over creating a new
instance of the Array
class.
const friendsWithSugar = []
const friendsWithoutSugar = new Array()
One thing you might have never thought about is how does every instance of an array have all of those built in methods (splice
, slice
, pop
, etc)?
Well as you now know, it's because those methods live on Array.prototype
and when you create a new instance of Array
, you use the new
keyword which sets up that delegation to Array.prototype
on failed lookups.
We can see all the array's methods by simply logging Array.prototype
.
console.log(Array.prototype)
/*
concat: Æ’n concat()
constructor: Æ’n Array()
copyWithin: Æ’n copyWithin()
entries: Æ’n entries()
every: Æ’n every()
fill: Æ’n fill()
filter: Æ’n filter()
find: Æ’n find()
findIndex: Æ’n findIndex()
forEach: Æ’n forEach()
includes: Æ’n includes()
indexOf: Æ’n indexOf()
join: Æ’n join()
keys: Æ’n keys()
lastIndexOf: Æ’n lastIndexOf()
length: 0n
map: Æ’n map()
pop: Æ’n pop()
push: Æ’n push()
reduce: Æ’n reduce()
reduceRight: Æ’n reduceRight()
reverse: Æ’n reverse()
shift: Æ’n shift()
slice: Æ’n slice()
some: Æ’n some()
sort: Æ’n sort()
splice: Æ’n splice()
toLocaleString: Æ’n toLocaleString()
toString: Æ’n toString()
unshift: Æ’n unshift()
values: Æ’n values()
*/
The exact same logic exists for Objects as well. Alls object will delegate to Object.prototype
on failed lookups which is why all objects have methods like toString
and hasOwnProperty
.
Static Methods
Up
until this point we've covered the why and how of sharing methods
between instances of a Class. However, what if we had a method that was
important to the Class, but didn't need to be shared across instances?
For example, what if we had a function that took in an array of Animal
instances and determined which one needed to be fed next? We'll call it nextToEat
.
function nextToEat (animals) {
const sortedByLeastEnergy = animals.sort((a,b) => {
return a.energy - b.energy
})
return sortedByLeastEnergy[0].name
}
It doesn't make sense to have nextToEat
live on Animal.prototype
since we don't want to share it amongst all instances. Instead, we can think of it as more of a helper method. So if nextToEat
shouldn't live on Animal.prototype
, where should we put it? Well the obvious answer is we could just stick nextToEat
in the same scope as our Animal
class then reference it when we need it as we normally would.
class Animal {
constructor(name, energy) {
this.name = name
this.energy = energy
}
eat(amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
sleep(length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
play(length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
}
function nextToEat (animals) {
const sortedByLeastEnergy = animals.sort((a,b) => {
return a.energy - b.energy
})
return sortedByLeastEnergy[0].name
}
const leo = new Animal('Leo', 7)
const snoop = new Animal('Snoop', 10)
console.log(nextToEat([leo, snoop])) // Leo
Now this works, but there's a better way.
Whenever
you have a method that is specific to a class itself, but doesn't need
to be shared across instances of that class, you can add it as a static
property of the class.
class Animal {
constructor(name, energy) {
this.name = name
this.energy = energy
}
eat(amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
sleep(length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
play(length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
static nextToEat(animals) {
const sortedByLeastEnergy = animals.sort((a,b) => {
return a.energy - b.energy
})
return sortedByLeastEnergy[0].name
}
}
Now, because we added nextToEat
as a static
property on the class, it lives on the Animal
class itself (not its prototype) and can be accessed using Animal.nextToEat
.
const leo = new Animal('Leo', 7)
const snoop = new Animal('Snoop', 10)
console.log(Animal.nextToEat([leo, snoop])) // Leo
Because we've followed a similar pattern throughout this
post, let's take a look at how we would accomplish this same thing
using ES5. In the example above we saw how using the static
keyword would put the method directly onto the class itself. With ES5,
this same pattern is as simple as just manually adding the method to the
function object.
function Animal (name, energy) {
this.name = name
this.energy = energy
}
Animal.prototype.eat = function (amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
Animal.prototype.sleep = function (length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
Animal.prototype.play = function (length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
Animal.nextToEat = function (nextToEat) {
const sortedByLeastEnergy = animals.sort((a,b) => {
return a.energy - b.energy
})
return sortedByLeastEnergy[0].name
}
const leo = new Animal('Leo', 7)
const snoop = new Animal('Snoop', 10)
console.log(Animal.nextToEat([leo, snoop])) // Leo
Getting the prototype of an object
Regardless of whichever pattern you used to create an object, getting that object's prototype can be accomplished using the Object.getPrototypeOf
method.
function Animal (name, energy) {
this.name = name
this.energy = energy
}
Animal.prototype.eat = function (amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
Animal.prototype.sleep = function (length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
Animal.prototype.play = function (length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
const leo = new Animal('Leo', 7)
const prototype = Object.getPrototypeOf(leo)
console.log(prototype)
// {constructor: Æ’, eat: Æ’, sleep: Æ’, play: Æ’}
prototype === Animal.prototype // true
There are two important takeaways from the code above.
First, you'll notice that proto
is an object with 4 methods, constructor
, eat
, sleep
, and play
. That makes sense. We used getPrototypeOf
passing in the instance, leo
getting back that instances' prototype, which is where all of our methods are living. This tells us one more thing about prototype
as well that we haven't talked about yet. By default, the prototype
object will have a constructor
property which points to the original function or the class that the
instance was created from. What this also means is that because
JavaScript puts a constructor
property on the prototype by default, any instances will be able to access their constructor via instance.constructor
.
The second important takeaway from above is that Object.getPrototypeOf(leo) === Animal.prototype
. That makes sense as well. The Animal
constructor function has a prototype property where we can share methods across all instances and getPrototypeOf
allows us to see the prototype of the instance itself.
function Animal (name, energy) {
this.name = name
this.energy = energy
}
const leo = new Animal('Leo', 7)
console.log(leo.constructor) // Logs the constructor function
To tie in what we talked about earlier with Object.create
, the reason this works is because any instances of Animal
are going to delegate to Animal.prototype
on failed lookups. So when you try to access leo.constructor
, leo
doesn't have a constructor
property so it will delegate that lookup to Animal.prototype
which indeed does have a constructor
property. If this paragraph didn't make sense, go back and read about Object.create
above.
You may have seen __proto__ used before to get an instances' prototype. That's a relic of the past. Instead, use Object.getPrototypeOf(instance) as we saw above.
Determining if a property lives on the prototype
There
are certain cases where you need to know if a property lives on the
instance itself or if it lives on the prototype the object delegates to.
We can see this in action by looping over our leo
object we've been creating. Let's say the goal was the loop over leo
and log all of its keys and values. Using a for in
loop, that would probably look like this.
function Animal (name, energy) {
this.name = name
this.energy = energy
}
Animal.prototype.eat = function (amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
Animal.prototype.sleep = function (length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
Animal.prototype.play = function (length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
const leo = new Animal('Leo', 7)
for(let key in leo) {
console.log(`Key: ${key}. Value: ${leo[key]}`)
}
What would you expect to see? Most likely, it was something like this -
Key: name. Value: Leo
Key: energy. Value: 7
However, what you saw if you ran the code was this -
Key: name. Value: Leo
Key: energy. Value: 7
Key: eat. Value: function (amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
Key: sleep. Value: function (length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
Key: play. Value: function (length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
Certainly! Here's a rewritten version:
"Why is this the case? Well, when using a for-in loop, it iterates over all enumerable properties of both the object and its prototype. Since, by default, any property added to a function's prototype is enumerable, we end up seeing not only the 'name' and 'energy' properties but also all the methods on the prototype, such as 'eat,' 'sleep,' and 'play.' To address this issue, we have two options: either specify that all prototype methods are non-enumerable, or find a way to only log to the console if the property belongs to the object itself and not to the prototype it delegates to in case of failed lookups. This is where 'hasOwnProperty' comes into play.
'hasOwnProperty' is a property present on every object that returns a boolean value, indicating whether the object possesses the specified property as its own, rather than inheriting it from the prototype. This is precisely what we need. Armed with this understanding, we can now modify our code to incorporate 'hasOwnProperty' within our for-in loop."
...
const leo = new Animal('Leo', 7)
for(let key in leo) {
if (leo.hasOwnProperty(key)) {
console.log(`Key: ${key}. Value: ${leo[key]}`)
}
}
And now what we see are only the properties that are on the leo
object itself rather than on the prototype leo
delegates to as well.
Key: name. Value: Leo
Key: energy. Value: 7
If you're still a tad confused about hasOwnProperty
, here is some code that may clear it up.
function Animal (name, energy) {
this.name = name
this.energy = energy
}
Animal.prototype.eat = function (amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
Animal.prototype.sleep = function (length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
Animal.prototype.play = function (length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
const leo = new Animal('Leo', 7)
leo.hasOwnProperty('name') // true
leo.hasOwnProperty('energy') // true
leo.hasOwnProperty('eat') // false
leo.hasOwnProperty('sleep') // false
leo.hasOwnProperty('play') // false
Check if an object is an instance of a Class
At times, you may need to determine if an object belongs to a particular class. In such situations, the instanceof operator can be employed. While the concept is straightforward, the syntax may seem a bit unusual, especially if you are encountering it for the first time. Here's how it functions:
object instanceof Class
The statement above will return true if object
is an instance of Class
and false if it isn't. Going back to our Animal
example we'd have something like this.
function Animal (name, energy) {
this.name = name
this.energy = energy
}
function User () {}
const leo = new Animal('Leo', 7)
leo instanceof Animal // true
leo instanceof User // false
The way that instanceof
works is it checks for the presence of constructor.prototype
in the object's prototype chain. In the example above, leo instanceof Animal
is true
because Object.getPrototypeOf(leo) === Animal.prototype
. In addition, leo instanceof User
is false
because Object.getPrototypeOf(leo) !== User.prototype
.
Creating new agnostic constructor functions
Can you spot the error in the code below?
function Animal (name, energy) {
this.name = name
this.energy = energy
}
const leo = Animal('Leo', 7)
Even seasoned JavaScript developers will sometimes get tripped up on the example above. Because we're using the pseudoclassical pattern
that we learned about earlier, when the Animal
constructor function is invoked, we need to make sure we invoke it with the new
keyword. If we don't, then the this
keyword won't be created and it also won't be implicitly returned.
As a refresher, the commented out lines are what happens behind the scenes when you use the new
keyword on a function.
function Animal (name, energy) {
// const this = Object.create(Animal.prototype)
this.name = name
this.energy = energy
// return this
}
This seems like too important of a detail to leave up to
other developers to remember. Assuming we're working on a team with
other developers, is there a way we could ensure that our Animal
constructor is always invoked with the new
keyword? Turns out there is and it's by using the instanceof
operator we learned about previously.
If the constructor was called with the new
keyword, then this
inside of the body of the constructor will be an instanceof
the constructor function itself. That was a lot of big words. Here's some code.
function Animal (name, energy) {
if (this instanceof Animal === false) {
console.warn('Forgot to call Animal with the new keyword')
}
this.name = name
this.energy = energy
}
Now instead of just logging a warning to the consumer of the function, what if we re-invoke the function, but with the new
keyword this time?
function Animal (name, energy) {
if (this instanceof Animal === false) {
return new Animal(name, energy)
}
this.name = name
this.energy = energy
}
Now regardless of if Animal
is invoked with the new
keyword, it'll still work properly.
Re-creating Object.create
In this article, we have extensively utilized Object.create to generate objects that inherit from the prototype of the constructor function. By now, you should be familiar with incorporating Object.create into your code. However, it's crucial to delve into the inner workings of Object.create. To gain a deeper understanding of its functionality, we will embark on the process of recreating Object.create. Let's start by examining what we already comprehend about the functioning of Object.create.
- It takes in an argument that is an object.
- It creates an object that delegates to the argument object on failed lookups.
- It returns the new created object.
Let's start off with #1.
Object.create = function (objToDelegateTo) {
}
Simple enough.
Now #2 - we need to create an
object that will delegate to the argument object on failed lookups. This
one is a little more tricky. To do this, we'll use our knowledge of how
the new
keyword and prototypes work in JavaScript. First, inside the body of our Object.create
implementation, we'll create an empty function. Then, we'll set the
prototype of that empty function equal to the argument object. Then, in
order to create a new object, we'll invoke our empty function using the new
keyword. If we return that newly created object, that'll finish #3 as well.
Object.create = function (objToDelegateTo) {
function Fn(){}
Fn.prototype = objToDelegateTo
return new Fn()
}
Wild. Let's walk through it.
When a new function, denoted as Fn in the provided code, is created, it automatically includes a prototype property. Upon invocation using the new keyword, the result is an object that will refer to the function's prototype in case of failed lookups. By altering the function's prototype, we gain control over the object to which the delegation occurs during unsuccessful lookups. In the given example, we override Fn's prototype with the object passed in during the invocation of Object.create, referred to as objToDelegateTo.
It's essential to note that in our example, support is provided for a single argument in Object.create. The official implementation also accommodates a second, optional argument that enables the addition of more properties to the created object.
Arrow Functions
Arrow functions don't have their own this
keyword. As a result, arrow functions can't be constructor functions and if you try to invoke an arrow function with the new
keyword, it'll throw an error.
const Animal = () => {}
const leo = new Animal() // Error: Animal is not a constructor
Also, because we demonstrated above that the
pseudoclassical pattern can't be used with arrow functions, arrow
functions also don't have a prototype
property.
const Animal = () => {}
console.log(Animal.prototype) // undefined
No comments:
Post a Comment