The 'new' keyword - Object Creation in JavaScript P4 - FunFunFunction #50

Fun Fun Function · Beginner ·☁️ DevOps & Cloud ·9y ago

Key Takeaways

Explains how the 'new' keyword works in JavaScript for object creation

Full Transcript

good Monday morning I M mpj and you are watching fun fun function today we're going to continue our series on object Creation in JavaScript and we're going to explore the new keyword we are going to talk about new when it is applied to functions we're not going to talk about uh new being applied to class because class uh is a New Concept in ecmascript in ecmascript 6 and in order to understand how that works you we need to go back and understand a little bit of History uh and how classes were faked in uh ecmascript 5 I want to stress that this is a series uh if you start watching this episode before watching any of the others you're going to be confused because these build on top of each other you can find the full uh uh playlist by clicking in the episode description this series is a deep dive in uh object creation on JavaScript uh you are not going to if you just want to quickly learn how to create object in JavaScript and and get started you know like this is not the series for you this is if you're like been working with JavaScript for a year or two and you really want to understand these things from the fundamental level basically we're geeking out seriously about object creation here uh be warned let me you oh it'sing break let me show you what I mean by new apply to functions uh so that you know exactly what I'm referring to you might have seen this uh on when you're trying to learn uh how to do uh when you first Google how to do a class in JavaScript this is generally what you find it's going to be a function and it's going to be like an object say a a uh person and um perhaps that person has a saying and you're assigning that to this it's going to be saying saying yeah and then you're going to see something like this person do Proto type talk and it's going to be function and it's going to say this dot saying say the console log and it's going to be I say like this and then we instantiate a person uh we're going to use VAR because these uh these examples um are in xmpt 5 uh and it's going to be like Croc for and it's going to be new person and it's going to be uh semicolons one one one cook forward and we are going to in then go cocord Dot uh talk and we're going to run that node. example JS Bon and it's going to say I say semicolons 111111111111 if you don't get the crockford joke it's a it's a guy in the JavaScript community that has been active in JavaScript for a very very long time and he's famous for a book called JavaScript the good parts and he really doesn't like uh the omittance of semicolons in JavaScript I tend to Omit them uh which annoys a lot of people because they've read uh what crockford said uh and there's there's actually a video on the whole semicolon issue that I made just so that I wouldn't have to reply all over and over again um you can find it in the episode description why should we even bother learning this why not simply just learn the class keyword and uh forget all this old stuff in ecmascript 5 and that's old just yes forget about that well for I can think of at least four reasons the first one is that you are going to uh run across this this is is code that you will find as you progress as a JavaScript developer JavaScript is a language that has been around for a very long time so if you're a professional developer you're going to run across code that is written in a style that is not the absolute most recent version of JavaScript and if you want to move from being a okay developer to a great developer you need to be able to deal with all kinds of code Old code included uh the second important reason that you might want to learn uh how this works is that uh the class keyword uses this technique under the hood so the class keyword is really just a thin syntactic sugar that actually does this uh behind the scenes and the class keyword in metascript 6 is a bit of a so-called leaky abstraction which means that you're going to see bits and Bobs of of this technique sticking out uh even if you just use uh the class keyword exclusively and uh if you don't understand what is going on under the hood it's kind of confus yeah the Third third reason is that we in order to understand our present we need to understand our history if you uh if you don't understand where JavaScript is coming from how things were added on top of each other and you know where stuff came from you don't you have you will have a much harder time to understand why the language looks as it does this is true with the world in general of course but it's especially valuable in programming to understand the history of things and fourth because we're in this series we're just geeking out about learning every nook and cranny about the language this feature is in the language uh it's there it's not the most modern way of doing things but it's not deprecated it's not removed it is there and we want to understand JavaScript fully because we want to be experts because that feels good okay but you want to know what what exactly exactly is it that new do do does I don't I'm not a native English also this place is so messy like it looks kind of clean because it's just shooting the only area in this office that is not a complete mess the desk is a mess just piles of stuff and there's paper all over the floor and he just oh I really need to clean but I just got back from two conferences and but I digress uh so what happens here when we call new person what what exactly is going on well new is going to do a couple of things the first thing the first order of business that new does is that it creates a new object just a plain object no nothing no properties no nothing second order of business is that it's going to look at whatever we have called new on and it's going to check that uh that object's prototype property here uh and it's going to set the Prototype of the new object that it just has created to be uh that object third it's going to again look at what we called newon this uh this function uh that I'm now going to refer to as the Constructor and and it's going to call that uh that function but it's going to call it with uh the new object that it created in step one uh assigned to the this variable here the fourth and final step that new uh takes is to return the new object that uh it created and then set the Prototype of and then executed The Constructor with as where the object was set as this and then it returns to object and that is what we get here as into that we assigned to the crockford variable and then call call talk on so this is the way that classes are faked in ecmascript 6 if the Prototype part confuses you it's because you have cheated and not watched the previous episodes in the series you can find the series playlist by clicking below if you don't prototypes and have not watched the previous episodes on prototypes this episode is just going to confuse you but even if you know prototypes this was a little bit confusing uh so we're going to go really slow here and what I'm going to do is that I'm going to pretend that new keyword uh that that that new did not exist and we would have to build it uh with as a function instead so that's what we're going to do uh we're going to just call new here so there and then we're going to declare the function uh new and we're going to rebuild new for me rebuilding something uh on my own is often a great way of understanding how something works so again we're going through the four things that new does the first thing is that we want to create a new object so let's let's do that that we're going to Bar uh we're going to call this uh op and it's a new object woo we have completed one of the four things that uh new does number two we're going to set the Prototype now we learned how to do this in the last episode uh the Prototype episode uh we're going to call object do set prototype of OB and we're going to set it to the conru do prototype and the first argument that we're going to give to new is the Constructor and now when I look at it look here this does not make sense because we're calling uh person here that that won't be possible uh we need to instead do this or it's not going to make sense so the the first argument that we pass to our implementation of new is the Constructor Constructor Constructor and the second argument is going to be whatever arguments that we want to be passed to the Constructor so we're setting the Prototype here uh we're setting the Prototype of object to do whatever object is on the Prototype property of the Constructor and and remember that we're passing in person here as the Constructor uh and the person here like the Prototype property we're setting talk and the talk property on that object so we're building out the property prototype here and prototype is a special property on every uh function object that you're creating because function is an object in JavaScript it's a bit mindblowing but whenever a function object in JavaScript is created it has this uh prototype uh property automatically I'm not sure if it has it for any other reason than to support this thing I don't think so uh please comment in the in the comments if you know uh know for any other reason why but either way with this line uh we we now completed the second uh criteria that that second step that new does which is to set the Prototype the third thing that new uh does that we need to reimplement in our reimplementation of new is to execute the Constructor with this set to the new objects that we had created okay this is going to be a little bit weird uh so we're going to take the Constructor and we are going to call apply on it now you might or might not be familiar with apply um you can think of it uh as a bind except that it executes the function immediately and returns its value and if you're not familiar with bind it's because you have not watched the previous episodes in the series click the descript ion the first argument that we give apply is going to be the object that we want to be have set as this and remember that this is going to be the object that we just have created the one the new object here the second argument that apply takes is an array of the arguments that we want to call the function with so in the case of the uh the person Constructor here uh it's going to be an array with just one uh item the saying so it's going to be you know uh this is in practice what we're going to be uh sorry that is what we're going to be passing in oh by the way I just noticed that we have one parenthesis too much down here so how do we actually create this thing dynamically here because we can't have it hardcoded like this that's not a proper implementation of of new um we are passing uh the first argument here like that's a Constructor and then it's going to be like the arguments uh that we're passing uh want pass to the Constructor so here is a bunch of arguments uh let me let me let's actually execute these things I'm going to comment these two lines out and I'm going to start teaching you if you don't already know it about the arguments keyword let's run this no example Jaz and see it boom break horrendously unexpected token new all right yeah so what since new is a reserved keyword we can't actually call this new uh let's call it something else let's call it a spawn spawn more crockford overlords um let's run that again not example JS all right now it logs out the consolate log arguments and it logs out this thing this is what the arguments look like so it's an almost array this is a super annoying design thingy in JavaScript uh uh that arguments is not actually an array object and it's kind of sort of an array it has for instance it does have a length property I think if I log out length it's going to be uh two yeah but it isn't an array so because you know we we want to get rid of this first argument here uh from the array before passing it to uh apply we just want this one and whatever comes after it if we have multiple arguments uh so uh we we would probably reach for something like slice which would give us like I think it's I think we can do that uh that is what we let me clear this this uh and we going to call node example Jazz and we're going to find out that oh arguments does not have a slice function because it's not an array so we need to convert uh arguments to an array first call it V orgs array if this was ecmascript 6 uh we could use array from uh and just call arguments and let's log that out see if that worked ORS array not example yeah right now we actually get something that looks like an array and we could then call Slice on it and and yes slice from index one which will give us yes the semicolons let me adjust my terminal a little bit because it's annoying me [Music] all right that's better and now we could pass uncomon this and pass in the uh the the sliced semicolons arguments array to the the apply function but we want to do this in ecmascript 5 for consistency reasons because we're doing a bit of a history lesson here uh and in uh in reascript 5 array. fromom does not exist so when you don't have array. from this is how you did it back in the day uh you go uh you go to the uh array object uh and you locate the Prototype property and you uh access the slice function that's on there and then you apply call that with the arguments property as this so slice is actually generic it doesn't require its this to be an array object and I suspect that that is partially because so that you can use it like this either way let's remove the array from with our new like retro way of creating an array out of arguments and then we slice those arguments to get rid of this one like the the Constructor the first argument here so like getting rid of this so that we get just this which we then pass to apply which means that Constructor is being called with the saying the semicolons 111 which brings us to the fourth thing that new does it's going to return the created object return OB no and I think that this might actually work now let's let's run it node ex node node example.js I say semicolons [Applause] 11111 we just implemented new uh there is one more weirdness with this that we need to implement uh because I lied uh it's actually sometimes here because there there is an edge case um if the Constructor returns an object uh if it returns I don't know I don't know exactly why you would ever do this but it is the behavior like if I return some object true some some object here that is going to be returned as crockford instead so if I uh if I do so I guess that we should do something like this we're going to return this or the object this is going to be a correct implementation so if I do know example J this is going to give us an error because uh crockford do talk is is is is not a function because it has returned the the dumb object true I'm just going to uh demonstrate this to you console.log H hello and I'm going to return log out the cocf object going to node uh oh sorry node example jazz uh and if I scroll up you see that hello and it has returned the Dum object and this is again this is actually what it's like so if I return and not use our spawn method and instead call new as um in in the standard way like the native implementation and I'm going to REM and I run it node example JS you see that yes that is actually what it does it does return uh the whatever object that the Constructor returns if it's if it happens to return return something super weird but that's the way it behaves back and node example Jazz I say semicolons one1 and we revert to our spawn cool and I'm going to do that again example G and it's the same behavior this is how uh new works on the inside so we talked about the new keyword more specifically how new is applied to functions not to classes because that's the es5 way of doing it uh and it's important to learn history and we have like delv into what exactly new does first thing it does is to create a new object then it sets the Prototype third it executes the Constructor with this set to the uh object that it created in step one and finally it Returns the created uh object unless the Constructor returns an object and then it will return that instead is there anything that was unclear uh please post an a comment down down below and also if you feel like you're confident with these things have a look at the comments below and find uh a person that is not clear on them and help them out because that is the absolutely best way that you can learn and grow as a programmer is but helping others you have you have watched an episode of fun fun function I release new episodes like this one every Monday morning at 0800 GMT I am mpj that's the Twitter bird there until next Monday morning stay curious

Original Description

💖 Support the show by becoming a Patreon https://www.patreon.com/funfunfunction We explore the new keyword in JavaScript works when applied to functions. This is the old school way of faking classes in JavaScript, prior to the class keyword being introduced in ES6. (We are going to be looking at the JavaScript ES6 class keyword later in this series) # Stuff mentioned in the video: • Code from the episode https://gist.github.com/mpj/2a6bd3ec1f9d327a1692b7bb56ad4e76 • Full series: Object creation in JavaScript https://goo.gl/pCt2tX • Book: JavaScript the good parts http://amzn.to/2cLGS3p (affiliate link - buying via this gives mpj moneys) • Episode mentioned: Semicolons cannot save you https://goo.gl/hEaned • Music in the video: Peacock by 7 minutes dead https://www.youtube.com/watch?v=Mi-xOhMqrkg # Hotspots 04:16 Why learn about new in JavaScript 07:58 What does new in JavaScript do 13:40 Apply in JavaScript 15:20 Arguments keyword in JavaScript 17:20 Array.from in JavaScript 22:13 Summary 💛 Follow on Twitch and support by becoming a Subscriber We record the show live Mondays 7 AM PT https://twitch.tv/funfunfunction 💛 Fun Fun Forum Private discussion forum with other viewers in between shows. https://www.funfunforum.com. Available to patron members, become one at https://www.patreon.com/funfunfunction 💛 mpj on Twitter https://twitter.com/mpjme 💛 CircleCI (Show sponsor) Robust and sleek Docker-based Continuous Integration as a service. I used CircleCI prior to them becoming a sponsor and I love that their free tier is powerful enough for small personal projects, even if they are private. Use this link when you sign up to let them know you came from here: https://circleci.funfunfunction.com 💛 Quokka (Show sponsor) Wonder how MPJ evaluates JavaScript inline his editor. Quokka is the answer - use this link when you buy to let them know you came from here: http://quokka.funfunfunction.com 💛 FUN FUN FUNCTION Since 2015, Fun Fun Function (FFF) is one o
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Fun Fun Function · Fun Fun Function · 55 of 60

1 Higher-order functions - Part 1 of Functional Programming in JavaScript
Higher-order functions - Part 1 of Functional Programming in JavaScript
Fun Fun Function
2 Map - Part 2 of Functional Programming in JavaScript
Map - Part 2 of Functional Programming in JavaScript
Fun Fun Function
3 Reduce basics - Part 3 of Functional Programming in JavaScript
Reduce basics - Part 3 of Functional Programming in JavaScript
Fun Fun Function
4 Destructuring: What, Why and How - Part 1 of ES6 JavaScript Features
Destructuring: What, Why and How - Part 1 of ES6 JavaScript Features
Fun Fun Function
5 Reduce Advanced - Part 4 of Functional Programming in JavaScript
Reduce Advanced - Part 4 of Functional Programming in JavaScript
Fun Fun Function
6 Closures - Part 5 of Functional Programming in JavaScript
Closures - Part 5 of Functional Programming in JavaScript
Fun Fun Function
7 Too many tools and frameworks!
Too many tools and frameworks!
Fun Fun Function
8 Currying - Part 6 of Functional Programming in JavaScript
Currying - Part 6 of Functional Programming in JavaScript
Fun Fun Function
9 Recursion - Part 7 of Functional Programming in JavaScript
Recursion - Part 7 of Functional Programming in JavaScript
Fun Fun Function
10 Promises - Part 8 of Functional Programming in JavaScript
Promises - Part 8 of Functional Programming in JavaScript
Fun Fun Function
11 Staying relevant as a programmer
Staying relevant as a programmer
Fun Fun Function
12 Factory Functions in JavaScript
Factory Functions in JavaScript
Fun Fun Function
13 Composition over Inheritance
Composition over Inheritance
Fun Fun Function
14 Software needs to be better - FunFunFunction #1
Software needs to be better - FunFunFunction #1
Fun Fun Function
15 Unit testing: How to get your team started - FunFunFunction #2
Unit testing: How to get your team started - FunFunFunction #2
Fun Fun Function
16 Straight-line code over functions - FunFunFunction #3
Straight-line code over functions - FunFunFunction #3
Fun Fun Function
17 Clojure - FunFunFunction #5
Clojure - FunFunFunction #5
Fun Fun Function
18 The growth stages of a programmer - FunFunFunction #6
The growth stages of a programmer - FunFunFunction #6
Fun Fun Function
19 5 tips to quickly understand a new code base - FunFunFunction #7
5 tips to quickly understand a new code base - FunFunFunction #7
Fun Fun Function
20 Semicolons cannot save you! - FunFunFunction #9
Semicolons cannot save you! - FunFunFunction #9
Fun Fun Function
21 Functors - FunFunFunction #10
Functors - FunFunFunction #10
Fun Fun Function
22 Functors: I was WRONG! - FunFunFunction #11
Functors: I was WRONG! - FunFunFunction #11
Fun Fun Function
23 Questions and Answers - FunFunFunction #12
Questions and Answers - FunFunFunction #12
Fun Fun Function
24 Streams - FunFunFunction #13
Streams - FunFunFunction #13
Fun Fun Function
25 Prototypes in JavaScript - FunFunFunction #16
Prototypes in JavaScript - FunFunFunction #16
Fun Fun Function
26 Fast or Flexible? - FunFunFunction #17
Fast or Flexible? - FunFunFunction #17
Fun Fun Function
27 Coders are herd animals - FunFunFunction #18
Coders are herd animals - FunFunFunction #18
Fun Fun Function
28 Weekend Kubernetes Shenanigans - FunFunFunction #19
Weekend Kubernetes Shenanigans - FunFunFunction #19
Fun Fun Function
29 Monad - FunFunFunction #21
Monad - FunFunFunction #21
Fun Fun Function
30 Moar Weekend Shenanigans - FunFunFunction #23
Moar Weekend Shenanigans - FunFunFunction #23
Fun Fun Function
31 Questions and Answers - FunFunFunction #24
Questions and Answers - FunFunFunction #24
Fun Fun Function
32 Losing motivation - FunFunFunction #25
Losing motivation - FunFunFunction #25
Fun Fun Function
33 LONGEST KUBERNETES SHENANIGANS! - FunFunFunction #26
LONGEST KUBERNETES SHENANIGANS! - FunFunFunction #26
Fun Fun Function
34 Fast code is NOT important - FunFunFunction #27
Fast code is NOT important - FunFunFunction #27
Fun Fun Function
35 Pair Programming a Facebook Messenger Bot - FunFunFunction #28
Pair Programming a Facebook Messenger Bot - FunFunFunction #28
Fun Fun Function
36 Writing unit tests for personal projects? - FunFunFunction #29
Writing unit tests for personal projects? - FunFunFunction #29
Fun Fun Function
37 Let's Code a Pomodoro Button - FunFunFunction #30
Let's Code a Pomodoro Button - FunFunFunction #30
Fun Fun Function
38 What editor do you use? - FunFunFunction #31
What editor do you use? - FunFunFunction #31
Fun Fun Function
39 Arrow functions in JavaScript - What, Why and How - FunFunFunction #32
Arrow functions in JavaScript - What, Why and How - FunFunFunction #32
Fun Fun Function
40 Is Programming Art? - MPJ's Musings - FunFunFunction #33
Is Programming Art? - MPJ's Musings - FunFunFunction #33
Fun Fun Function
41 Generators in JavaScript - What, Why and How - FunFunFunction #34
Generators in JavaScript - What, Why and How - FunFunFunction #34
Fun Fun Function
42 Haskell Basics - FunFunFunction #35
Haskell Basics - FunFunFunction #35
Fun Fun Function
43 Haskell - Baby's first functions - FunFunFunction #36
Haskell - Baby's first functions - FunFunFunction #36
Fun Fun Function
44 Is Big O relevant to you? - Q&A Part 1 - FunFunFunction #37
Is Big O relevant to you? - Q&A Part 1 - FunFunFunction #37
Fun Fun Function
45 How much are you allowed to Google? - Q&A Part 2 - FunFunFunction #38
How much are you allowed to Google? - Q&A Part 2 - FunFunFunction #38
Fun Fun Function
46 Haskell lists - FunFunFunction #39
Haskell lists - FunFunFunction #39
Fun Fun Function
47 var, let and const - What, why and how - ES6 JavaScript Features
var, let and const - What, why and how - ES6 JavaScript Features
Fun Fun Function
48 Why are some programming languages popular? - MPJ's Musings  - FunFunFunction #41
Why are some programming languages popular? - MPJ's Musings - FunFunFunction #41
Fun Fun Function
49 Does a developer need to be nice? - MPJ's Musings - FunFunFunction #42
Does a developer need to be nice? - MPJ's Musings - FunFunFunction #42
Fun Fun Function
50 bind and this - Object Creation in JavaScript P1 - FunFunFunction #43
bind and this - Object Creation in JavaScript P1 - FunFunFunction #43
Fun Fun Function
51 Examples of this and bind - Object Creation in JavaScript P2 -  FunFunFunction #44
Examples of this and bind - Object Creation in JavaScript P2 - FunFunFunction #44
Fun Fun Function
52 Prototype basics - Object Creation in JavaScript P3 - FunFunFunction #46
Prototype basics - Object Creation in JavaScript P3 - FunFunFunction #46
Fun Fun Function
53 Separation of concerns RANT - MPJ's Musings - FunFunFunction #47
Separation of concerns RANT - MPJ's Musings - FunFunFunction #47
Fun Fun Function
54 Cellular Automata - Pair Programming - FunFunFunction #49
Cellular Automata - Pair Programming - FunFunFunction #49
Fun Fun Function
The 'new' keyword - Object Creation in JavaScript P4 - FunFunFunction #50
The 'new' keyword - Object Creation in JavaScript P4 - FunFunFunction #50
Fun Fun Function
56 __proto__ vs prototype - Object Creation in JavaScript P5 - FunFunFunction #52
__proto__ vs prototype - Object Creation in JavaScript P5 - FunFunFunction #52
Fun Fun Function
57 Unity game pair programming - Let's code - FunFunFunction #53
Unity game pair programming - Let's code - FunFunFunction #53
Fun Fun Function
58 Throw out your tools - MPJ's Musings - FunFunFunction #54
Throw out your tools - MPJ's Musings - FunFunFunction #54
Fun Fun Function
59 Unit tests vs. Integration tests - MPJ's Musings - FunFunFunction #55
Unit tests vs. Integration tests - MPJ's Musings - FunFunFunction #55
Fun Fun Function
60 Object.create - Object Creation in JavaScript P6 - FunFunFunction #57
Object.create - Object Creation in JavaScript P6 - FunFunFunction #57
Fun Fun Function

Related AI Lessons

Chapters (6)

4:16 Why learn about new in JavaScript
7:58 What does new in JavaScript do
13:40 Apply in JavaScript
15:20 Arguments keyword in JavaScript
17:20 Array.from in JavaScript
22:13 Summary
Up next
Containers on Amazon ECS with Mama J
AWS Developers
Watch →