NDC Oslo 2012: Rediscovering JavaScript
This is a modal window.
Das Video konnte nicht geladen werden, da entweder ein Server- oder Netzwerkfehler auftrat oder das Format nicht unterstützt wird.
Formale Metadaten
Titel |
| |
Serientitel | ||
Anzahl der Teile | 110 | |
Autor | ||
Lizenz | CC-Namensnennung - keine kommerzielle Nutzung - Weitergabe unter gleichen Bedingungen 3.0 Unported: Sie dürfen das Werk bzw. den Inhalt zu jedem legalen und nicht-kommerziellen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen und das Werk bzw. diesen Inhalt auch in veränderter Form nur unter den Bedingungen dieser Lizenz weitergeben | |
Identifikatoren | 10.5446/51038 (DOI) | |
Herausgeber | ||
Erscheinungsjahr | ||
Sprache |
Inhaltliche Metadaten
Fachgebiet | ||
Genre | ||
Abstract |
|
00:00
SoftwareentwicklerFormale SpracheDynamisches SystemAlgebraisch abgeschlossener KörperFunktion <Mathematik>SchlussregelTwitter <Softwareplattform>VerschlingungE-MailSkriptspracheMultiplikationsoperatorBenutzerbeteiligungAppletCASE <Informatik>ResultanteFunktionale ProgrammierspracheWort <Informatik>CodeNachbarschaft <Mathematik>Prozess <Informatik>Leistung <Physik>Rechter WinkelBitInelastischer StoßEigentliche AbbildungSchlüsselverwaltungVariableSkriptspracheGeradeVererbungshierarchiePrototypingTypentheorieProgrammierspracheCodierungMereologieOrdnung <Mathematik>Geometrische FrustrationSchlussregelFormale SpracheTermSystemaufrufComputerspielCoxeter-GruppeWeb SiteProgrammierungKartesische KoordinatenZahlenbereichBildschirmmaskeWiderspruchsfreiheitBrowserSoftwareentwicklerGüte der AnpassungKonfiguration <Informatik>DatenstrukturVerschlingungRechenschieberComputeranimation
06:08
Funktion <Mathematik>Objektorientierte ProgrammierspracheIntegritätsbereichInstantiierungp-BlockSchlussregelFormale SprachePrototypingSpielkonsoleStellenringSoftwareentwicklerLogarithmusVariableStellenringRechter WinkelFunktionale ProgrammierspracheParametersystemFehlermeldungHochdruckSystemaufrufComputeranimation
06:59
LogarithmusSpielkonsoleFunktion <Mathematik>StellenringSoftwareentwicklerFunktionale ProgrammiersprachePunktVariableVarianzp-BlockCodeProgrammierspracheGüte der AnpassungProgrammiergerätAppletRechter WinkelMultiplikationsoperatorWort <Informatik>DifferenteDeklarative ProgrammierspracheProzess <Informatik>MAPFormale GrammatikProgrammierungSkriptspracheComputeranimationVorlesung/Konferenz
09:20
p-BlockFunktion <Mathematik>SchlussregelFormale SpracheObjektorientierte ProgrammierspracheSoftwareentwicklerIntegritätsbereichInstantiierungNP-vollständiges ProblemLogarithmusStellenringMAPp-BlockVariableFunktionale ProgrammierspracheSchreiben <Datenverarbeitung>EinsRelationentheorieCodeBenutzerbeteiligungCASE <Informatik>BitMultiplikationsoperatorParametersystemWiderspruchsfreiheitSystemaufrufDateiformatEreignishorizontComputeranimationVorlesung/Konferenz
11:28
Funktion <Mathematik>Objektorientierte ProgrammierspracheInstantiierungIntegritätsbereichSoftwareentwicklerp-BlockSchlussregelFormale SpracheFunktionale ProgrammierspracheLokales MinimumSpielkonsoleLogarithmusParametersystemFunktionale ProgrammierspracheZahlenbereichGeradeDateiformatWald <Graphentheorie>SkriptspracheLokales MinimumC sharpSystemaufrufAppletSichtenkonzeptPunktMultiplikationsoperatorLeistung <Physik>CompilerDifferenzkernVarianzMailing-ListeCASE <Informatik>DatensatzVariableArithmetisches MittelFormale SpracheDifferenteProzess <Informatik>UmfangWort <Informatik>WhiteboardCodeComputeranimationVorlesung/Konferenz
16:13
SpielkonsoleLokales MinimumFunktion <Mathematik>SoftwareentwicklerPhysikalischer EffektFunktionale ProgrammierspracheParametersystemDeklarative ProgrammierspracheAusnahmebehandlungCASE <Informatik>URLVariableArithmetisches MittelLokales MinimumDickeZahlenbereichKlasse <Mathematik>Rechter WinkelAppletWeb logSystemaufrufSkriptspracheKartesische Koordinatenp-BlockComputeranimation
18:08
Lokales MinimumSoftwareentwicklerParametersystemFunktion <Mathematik>SchlussregelFormale SpracheObjektorientierte ProgrammierspracheInstantiierungIntegritätsbereichCASE <Informatik>AppletCodeDifferenteZahlenbereichp-BlockAusnahmebehandlungKlasse <Mathematik>ParametersystemFunktionale ProgrammierspracheAdditionHochdruckBitSystemaufrufMessage-PassingComputeranimation
19:14
Funktion <Mathematik>SoftwareentwicklerSpielkonsoleComputervirusSystemaufrufFormale SpracheSchlussregelp-BlockInstantiierungIntegritätsbereichObjektorientierte ProgrammierspracheRechenwerkLogarithmusParametersystemOrdnung <Mathematik>Objektorientierte ProgrammierspracheCliquenweiteRechter WinkelFunktionale ProgrammierspracheBenutzerbeteiligungZeichenketteMessage-PassingRichtungZweiMereologieCASE <Informatik>Funktion <Mathematik>EreignishorizontCodeComputervirusSystemaufrufGruppenoperationKontextbezogenes SystemDiskrete UntergruppeMultiplikationsoperatorWeb-ApplikationWort <Informatik>Mailing-ListeProgrammierungNichtlinearer OperatorAppletBitFamilie <Mathematik>p-BlockForcingSkriptspracheCAN-BusVererbungshierarchieMultiplikationWarteschlangeHyperbelverfahrenGesetz <Physik>SoftwaretestComputeranimation
26:05
SoftwareentwicklerFunktion <Mathematik>Objektorientierte ProgrammierspracheInstantiierungIntegritätsbereichVererbungshierarchieIndexberechnungLogarithmusSpielkonsoleBitNichtlinearer OperatorCASE <Informatik>SkriptsprachePunktFunktionale ProgrammierspracheUmsetzung <Informatik>MultiplikationsoperatorObjektorientierte ProgrammiersprachePaarvergleichSelbstadjungierter OperatorResultanteMatchingWort <Informatik>VersionsverwaltungAggregatzustandParametersystemVorlesung/KonferenzComputeranimation
28:17
VererbungshierarchieFunktion <Mathematik>Objektorientierte ProgrammierspracheInstantiierungIntegritätsbereichIndexberechnungSoftwareentwicklerSpielkonsoleLogarithmusProgrammierungObjektorientierte ProgrammierspracheMultiplikationsoperatorRechter WinkelGreen-FunktionKlasse <Mathematik>Funktionale ProgrammierspracheWeb-ApplikationProgrammbibliothekSyntaktische AnalyseTeilmengeSystemaufrufWort <Informatik>Kategorie <Mathematik>GraphfärbungKartesische KoordinatenSkriptspracheProzess <Informatik>ForcingComputeranimation
30:49
Funktion <Mathematik>Objektorientierte ProgrammierspracheIntegritätsbereichInstantiierungVererbungshierarchieIndexberechnungSoftwareentwicklerSpielkonsoleLogarithmusTreiber <Programm>Klasse <Mathematik>ProgrammierungObjektorientierte ProgrammierspracheSystemaufrufFunktionale ProgrammierspracheParametersystemKonstruktor <Informatik>MultiplikationsoperatorBitPrototypingTypentheorieCASE <Informatik>Kette <Mathematik>HalbleiterspeicherKontextbezogenes SystemTermBetrag <Mathematik>ZweiInstantiierungPunktGüte der AnpassungAbstandLeistung <Physik>Rechter WinkelAbstimmung <Frequenz>UnrundheitSkriptspracheInformationWort <Informatik>GruppenoperationAppletProzess <Informatik>GradientBestimmtheitsmaßPlastikkarteIntelWhiteboardComputeranimation
37:40
LogarithmusSpielkonsoleSoftwareentwicklerFunktion <Mathematik>PrototypingPrototypingLaufzeitfehlerZeiger <Informatik>InstantiierungObjektorientierte ProgrammierspracheGeradeHochdruckHilfesystemMereologiePhysikalisches SystemAppletKategorie <Mathematik>Konfiguration <Informatik>ComputerspielVererbungshierarchieKlasse <Mathematik>ParametersystemVollständigkeitProgrammierumgebungFunktionale ProgrammierspracheSoftwaretestReelle ZahlSchnittmengeGemeinsamer SpeicherHalbleiterspeicherGüte der AnpassungRechter WinkelVarianzTreiber <Programm>SystemaufrufPunktProzess <Informatik>Wort <Informatik>PlastikkarteBitrateBestimmtheitsmaßTotal <Mathematik>TeilmengeCASE <Informatik>Endliche ModelltheorieFlächeninhaltMultiplikationSkriptspracheKontextbezogenes SystemÜberlagerung <Mathematik>VersionsverwaltungMathematikEinsBitComputeranimation
44:56
LogarithmusPrototypingSpielkonsoleCodePrototypingInstantiierungGeradeHochdruckKategorie <Mathematik>Objektorientierte ProgrammierspracheBit
45:45
PrototypingLogarithmusSoftwareentwicklerBimodulFlächeninhaltStichprobeFehlermeldungEreignishorizontObjektorientierte ProgrammierspracheFunktion <Mathematik>Prozess <Informatik>InstantiierungIntegritätsbereichVererbungshierarchieIndexberechnungKategorie <Mathematik>Funktion <Mathematik>Funktionale ProgrammierspracheComputeranimation
46:31
PrototypingSoftwareentwicklerLogarithmusSpielkonsoleKategorie <Mathematik>ZweiKategorie <Mathematik>CASE <Informatik>PlastikkarteObjektorientierte ProgrammiersprachePrototypingCodeSchnittmengeSystemaufrufGüte der AnpassungMereologieAbstandDifferenteZahlenbereichVererbungshierarchieGeradeVerknüpfungsgliedSkriptspracheBestimmtheitsmaßWort <Informatik>Funktionale ProgrammierspracheAppletLeistungsbewertungHochdruckPhysikalisches SystemMAPComputeranimationTafelbild
49:46
PrototypingSoftwareentwicklerMenütechnikFunktion <Mathematik>Funktionale ProgrammierspracheSkalarproduktVarianzObjektorientierte ProgrammierspracheGüte der AnpassungCASE <Informatik>MultiplikationsoperatorBestimmtheitsmaßRechter WinkelSpeicherabzugSchnittmengeComputeranimationVorlesung/Konferenz
50:57
Funktion <Mathematik>SoftwareentwicklerLogarithmusFunktionale ProgrammierspracheSkalarproduktEigentliche AbbildungKategorie <Mathematik>AusnahmebehandlungObjektorientierte ProgrammierspracheKlasse <Mathematik>Ganze FunktionHochdruckRechter WinkelCASE <Informatik>BestimmtheitsmaßSkriptspracheAppletWort <Informatik>Computeranimation
52:19
SpielkonsoleFunktion <Mathematik>LogarithmusSoftwareentwicklerPrototypingObjektorientierte ProgrammierspracheInstantiierungIntegritätsbereichVererbungshierarchieIndexberechnungKategorie <Mathematik>VererbungshierarchieFunktionale ProgrammierspracheParametersystemEin-AusgabeCASE <Informatik>NP-hartes ProblemQuadratzahlBenutzerbeteiligungObjektorientierte ProgrammierspracheVarianzMAPKartesische KoordinatenInstantiierungHochdruckVariableMultiplikationsoperatorBildschirmmaskeRichtungCodePoisson-KlammerPrototypingKlasse <Mathematik>Computeranimation
53:17
Funktion <Mathematik>SoftwareentwicklerLogarithmusPrototypingSpielkonsoleVererbungshierarchieStatistikParametersystemPrototypingFunktionale ProgrammierspracheSystemaufrufKlasse <Mathematik>CASE <Informatik>SkalarproduktObjektorientierte ProgrammierspracheAbstandHochdruckVererbungshierarchieKontextbezogenes SystemInstantiierungRoutingEin-AusgabeEndliche ModelltheorieTermIndexberechnungRechter WinkelNatürliche ZahlBitWort <Informatik>Computeranimation
56:19
VererbungshierarchieInstantiierungCodeIndexberechnungKategorie <Mathematik>AusnahmebehandlungFehlermeldungZeichenketteMereologieSoftwareentwicklerIndexberechnungMultiplikationsoperatorAbstraktionsebeneFormale SpracheMAPCodeAusnahmebehandlungKategorie <Mathematik>Schreiben <Datenverarbeitung>Array <Informatik>BitObjektorientierte ProgrammierspracheZahlenbereichSkriptspracheVerschlingungSpeicherabzugDruckspannungProzess <Informatik>
58:35
VerschlingungE-MailDynamisches SystemFormale SpracheSchlussregelSoftwareentwicklerTwitter <Softwareplattform>Funktion <Mathematik>Algebraisch abgeschlossener KörperComputeranimation
Transkript: Englisch(automatisch erzeugt)
00:02
Good morning. Welcome to the session on rediscovering JavaScript. My name is Venkat Subramanyam. We're going to talk about JavaScript, take a look at the, or relook at a language, talk a little bit about what's really good about this language, how to effectively use it. Best time to ask a question or make a comment is when you have it.
00:22
So please don't wait in the very end. If you do have a question, I have a challenge here. I'm kind of blinded by these lights over here. So if you do have a question, just start speaking up, draw my attention, then I'll be more than happy to listen to what you have to say and then respond to it. But please do ask questions, make comments along the way. Don't let me talk for too long, just alone.
00:44
We're going to talk about JavaScript. Let me start with a few things about JavaScript. I'm not going to use any slides in this presentation or any presentations this week. I'm going to just do some live coding, talk a little bit, maybe for a few minutes, get into code, play with some examples. You can download the code and examples from my website. The link is up there.
01:04
So let's get started. First of all, what's really wrong with JavaScript? JavaScript seems to be like this villain in the movie, right? You thought he's dead and he keeps coming back. And only more powerful today with all the things developing on the JavaScript side.
01:20
So it's a good idea to just pay attention to what it's doing. The first problem with JavaScript is the inconsistencies across the browsers, across the tools. And it can be overwhelming to develop applications with JavaScript. One of the other problems with JavaScript is, what a bad name. I mean, think about this for a minute. Would you do this to your kids?
01:41
Would you name your kid after a popular kid in the neighborhood? And how would your kid grow up with such a name, right? So that is kind of what one of the problems with JavaScript is, that it really took the name after Java, which was becoming popular those days. Now you're trying to distance away from the word Java, which is kind of silly, right? So it's also a poorly understood language.
02:03
And one of the reasons for that is, most of us learned about JavaScript by looking at code on the web. And most of the code on the web just sucks. So we really learned from bad examples, unfortunately. And that's one of the biggest problems with JavaScript itself. But that's enough of talking about what's bad about it.
02:22
Let's talk about what's good about JavaScript. JavaScript is a very powerful language. In fact, a little bit way too powerful in a lot of ways, that it becomes really hard to manage the language. And I want to spend a little bit of time about the power of the language and how we can effectively use it. It is a dynamically typed language. It is a language which is also weakly typed, sometimes garbage in, garbage out,
02:44
that poses a bit of a challenge as well as we develop code with it. It's extremely flexible. But one of the things that I really like about JavaScript is the functional style of coding. And when I talk about functional style, I'm not talking about the purity of functions really, but more so I'm really talking about the ability for us to use higher order functions.
03:02
We can create functions and pass it to functions, receive functions from functions, and create functions within functions as well. And that is one of the nice features of JavaScript. We'll talk about this more later on. The part that really excites me about JavaScript is the prototypal inheritance. And unlike the inheritance in languages like Java and C Sharp,
03:23
which is really static, prototypal inheritance is actually extremely powerful and makes it very easy for us to use. We'll certainly delve into prototypal inheritance quite a bit as we go on. There are parts of JavaScript that are really well formed, and there's a lot of JavaScript that is really poorly structured.
03:43
Douglas Cockford has a very interesting book called The JavaScript Good Parts. It's a very thin book. And it's a bit of frustration to read because there is only a few things we can really do correctly in JavaScript. And he cautions quite a bit about things we shouldn't do also in the book. But it's an important book to read to understand what is a good part of JavaScript we can actually make good use of.
04:03
So in terms of some of the things I want to talk about, let's talk about some ground rules in JavaScript. The first ground rule in JavaScript is JavaScript will tell you that there are some things that are optional, but don't be misled by the word optional. It's optional as in, if you don't use it, I'll hurt you, kind of optional.
04:22
So it's important for us to know what those things are. One of them, for example, is the semicolon, or the use of semicolon. Let's take a look at an example here. Let's say I have a function called foo, and in programming sessions you are required to use foo in some form, so I've cleared that requirement here. So I have a number coming in as an input,
04:41
and I'm going to say if n is less than five, I want to return over here, and I wonder what I want to return. Let's say return, I want to return n times two. On the other hand, if it is not, I want to go ahead and return, in this case, let's say just the value of n itself. So we could say simply return n.
05:00
Now this is one thing that kind of bothers me a little bit, is I've been programming more and more in languages today that don't require a use of return keyword, but JavaScript requires a return to be placed when you want to return stuff. So you may see me miss that a few times here along the way, but just remind me if I do. So I'm going to call foo, and I'm going to send maybe, let's say, a value of six.
05:22
Well, that's pretty simple. We can see that I'm going to send a value of six, it simply returned the value of six, not a big deal. What if I'm going to call this function one more time, but this time I'm going to pass a value of three? Well, of course, when I send three, three is less than five, so it would return three times two, which is again six itself,
05:40
but notice we got it undefined. And the reason for this is, when I did not put a semicolon, JavaScript said, let me help you, and puts a semicolon where you don't expect it to be. So as a result, it actually produces an incorrect result in this case, so you have to be a bit careful about semicolons and where you are placing them. So in this particular case,
06:01
you really want to specify the semicolon, but also make sure you break the line at the proper place, otherwise it becomes really problematic. But going forward with this, there is a way to define variables in JavaScript, we have to be very careful with. For example, let's say for a minute that I want to define a variable here. I'll call it local one equals, let's say, six,
06:21
and I want to simply print the value of local one right there. So I printed the value, so I'm going to call the function foo, which is simply going to print the value itself. I don't need to send any parameters right there. So you can see it's printing, but what if I try to print the value here, local one, outside of this function? That clearly gives us an error, as you can see,
06:43
because that variable is not in the scope. So that makes sense. But here's the question. What happens if I define a variable here, let's call it, you know, some variable g equals four, and I want to print the value of the variable g right here, so I printed it. So you can see the value of the variable being printed up here,
07:02
so within the function foo, but what if I call, and outside the function, I try to print the variable? Notice that I'm able to access that variable right here. So what's the difference? So if you declare a variable using a var, that variable becomes a local variable. If you forget to put var,
07:22
JavaScript sits there and thinks about, hmm, this programmer forgot to put a var, what's the worst thing I can do to hurt this programmer? And it decides a great way to do that is to make this variable global, right, because that messes up your code royally well. So it really makes variables global if you don't put a var,
07:40
so it's important for us to really declare variables with a var when we are using it. Another point to keep in mind when it comes to declaring variables is you may be tempted to do something like this based on your experience in languages like C sharp and Java, and that is to create a block variable, and then say over here, b equals four,
08:00
and you're trying to print this variable right here within this block. But what's going to happen if, notice that I used the var to declare it, but what if I come out of this block and try to use the value of b itself, notice that variable is still available to you. And the reason for this is, JavaScript really doesn't have a concept of block scope at all.
08:21
So in other words, when you use a function and you have variables defined within a function, all the variables really are being defined up here in the beginning, so b is actually being defined here, and the value for it is being assigned over here in reality. So in other words, this variable b is undefined
08:40
and it's bounded to this value four later on. So in other words, there's really no block scope. So when it comes to JavaScript, it's better to define variables at the very top of the function before you use them. This is kind of counter to how we are used to doing in Java and C sharp. This is back to the good old C days where we declare all the variables
09:01
before we really get into the function itself. Now you may say, wait a second, but if the function is very large, then I can't really know what these variables are at any given time. There's a very easy way to fix the problem. Don't write long functions, right? So JavaScript again has a few of these quirks built in that we have to really make the functions work in a certain way.
09:21
And so make sure you declare variables with a var, and of course, keep in mind that there's no block level variables. But how do you write functions? Functions can be written in about two and a half ways. I'm gonna say two ways, but there's a third way, which I say the half way, but I recommend not using it as often. But let's take a look at what are the different ways
09:41
to define functions itself. So one way to define a function is to do what I just did here, but what you normally see most often than not is something like function foo and a parameter being passed in. And you could say foo call, for example, and you could write something like this.
10:01
So in this case, you call the function foo, just like you do. And like I said, most of the time, you see code like this. But my preference mostly is to really define a function like a variable equals function. You define what the parameter to this function is, and then you specify whatever you want to call in this function. So I would say f1 called in this case.
10:22
And of course, to call this function, it's going to be very, you know, same as the other function itself, not very different. But this is a much preferred way to define functions. The reason for this is that it gives us a bit of a consistency in the code. There are times when you define functions standalone, but there are also times when you define functions
10:42
as really a function that is going to pass to other functions, like event handlers. And in that regard, the highlighted format is a little bit more flexible and more consistent to define. So that is my preferred way of writing functions in JavaScript, even though the top one is probably what you're going to see most of the code
11:01
written on the web. So but a third way is really to say f2 equals function. And this comes from the Department of Redundancy. You specify the name on both sides. And then you could specify this like this as well. And then you could say, for example, f2 called. Now in this particular case, this gives you an opportunity for you
11:20
to use the function within the function itself. So you may see this sometimes. But again, don't do that as often unless you have a very important reason to do that. So those are some of the ways to define functions in JavaScript. And like I said, my preference mostly is to really define it like the first way you saw. Sorry, the second way you saw,
11:41
which is really using this format here on line number 26. That's what I would prefer to define. Now what about arguments to functions? Let's take a look at an example of sending arguments to functions. So I'm going to say max is a function that takes two parameters, a and b, as the parameters. And I'm going to say if a is greater than b,
12:02
I want to return over here, let's say, a itself. Otherwise, I simply want to return b. So I want to call this function max. And I'm going to say send a value of, let's say, 5 and 2 as parameters. And I want it to print the value for us. So we'll just call that function. And as you can see, it printed this value.
12:22
But what if I call this with a max and let's say 1 and 7 as the second parameter being greater? So that seems to work just fine. But what if it's going to be a call to max, but I send 2, 3, and 4 as parameters? Notice I'm sending one extra parameter than what was expected up there.
12:42
Well, coming from the point of view of Java and C Sharp, you would have a compiler that slaps you on your wrist and says, you cannot pass three parameters to this function because only two of them are required in this particular function call. But this is JavaScript. When you call this, notice it simply ignored the last parameter at this point.
13:01
So JavaScript treats you like a guest in its house. It doesn't complain to you. It says, all right, all right, you sent me more than what's needed, but I'm not going to yell and scream at you for that. It politely moves on. But what's really going on in this case? But what if I call this function with only a value of 2? For example, rather than two parameters,
13:22
I only send one parameter. What's going to happen? Notice in this case, it said undefined to tell us that variable is undefined. So something is going on here. What's really happening? Well, what's really happening here is that the parameter list that you send to a function is defined very differently in the case of JavaScript.
13:41
In C Sharp and Java, for example, your parameter list is defined when you declare or define the function, but not so in the case of JavaScript. In the case of JavaScript, the parameter list for the function is defined at the time of the call rather than the time of the definition itself.
14:01
So right here, you're specifying that Max is taking two parameters. On the other hand, here you are saying, Max is taking three parameters. On the other hand, here you are saying, Max is taking only one parameter. So in other words, you define the parameter list for a function at the time of the call in the case of JavaScript.
14:20
Now, how do you really access these in the case of JavaScript? To understand this, you can think about this a little differently. For example, I've given names for two parameters. Think about a parameter list, for example, as the people in the first row. I can call him Thomas because I know him by name, but that doesn't mean he's the only one here.
14:41
There are several people in this room, but I chose to give a name associated with one person in here because I just recognized that person. So in that way, the parameter list that JavaScript uses is simply the parameter list. It contains as many parameters as you have specified. You could optionally choose to give names
15:01
for the first few parameters in the parameter list, and the remaining parameters simply are unnamed at this point, or you have not given a specific targeted name for these things. So to understand this, let's step back for a second and completely remove this. And instead, we will simply say over here, I'm going to call this with no parameters at all.
15:23
And I'm going to simply return, let's say, just a one for a minute. Of course, all these are broken at this point. We'll come back and fix it. But I'm going to simply print out arguments over here. So arguments, basically, is a special name for all the arguments within your function itself.
15:40
So as you can see in this code, when I printed out arguments, it tells me what the arguments are that are being passed to this function based on the call you just made. So you can see the real power of this language at this point. So I really want to navigate through these arguments. So I'm going to say var maximum equals.
16:00
So I'm going to create a maximum variable. Let's say this is going to be arguments 0 to begin with. And this is the first parameter in the arguments. And I want to simply return the maximum at the very end of the call itself. So I'm going to go to the arguments, basically. Let's see what I did wrong here. So I'm going to define maximum as a variable.
16:21
Let's just set this to a one for a minute. I want to return the maximum when I'm done. But I'm going to say arguments, right? So arguments is going to be my variable. And I'm going to get the first argument in this function. So you can see I'm returning just the first value. But I really want to get the maximum value. So I could say for i equals 0, i less than argument
16:44
start length of the arguments. And then we could specify an increment on the arguments. And then we could say if maximum is less than arguments at location i, then I want maximum to be arguments at location i. And then we can loop through and ask him to find the value in this particular case.
17:02
So you can see how that's being able to handle. And when you look at the function declaration itself, it doesn't tell you anything. But that doesn't mean the function doesn't take any arguments. It can take any number of arguments in this case. Now, of course, what's going to happen if I call this function without any parameters? You can see it really calls undefined
17:21
because argument 0 is undefined. And as a result, it says undefined. So the arguments collection is still sent to it. But it has empty collection. It doesn't have any data in it. If you really want to handle it, you certainly can handle it. You could say, for example, if arguments start length is going to be 0, for example,
17:41
then you could handle it. Maybe you can throw an exception throw. And in JavaScript, you can throw anything you want to throw. You don't have to throw an exception class. You can throw just about anything. It's kind of like being in a bad marriage, right? People throw all kinds of things at each other. So you can pretty much throw anything you want in JavaScript. So in this case, I can say, too bad, empty parameter.
18:06
And you can specify other details. So of course, in this case, I want to handle this exception. So you would do something very similar to what you do in C sharp. Our Java, you could say try block. And you could specify a catch and finally block. In this case, I have an exception I want to print.
18:22
So I could say exception. And you could also write a finally block if you're interested. And you could say whatever you want to handle in the finally block. So that resembles very similar to what you do in Java or C sharp. But one of the difference in this case is you don't have to have an exception class to throw. You can throw anything you want to throw.
18:42
And you can handle it in your code. So that gives you an example of how you could be working with arbitrary number of arguments in your code. And that's a very powerful concept, as you can see in this case. But in addition to the arguments, which is kind of like your hidden particular variable in your function, there are two other things
19:01
we need to be familiar with. One of them is a way to call this function with another additional parameter called the this parameter. Now, it may be a bit strange to think about what this is. But let's look at an example of what this could be. So I'm going to have a method called greet. And this takes a message, let's say a message over here.
19:21
And I want to print this message in capital letters or whatever it is. But I want to greet somebody. So let's say name over here for a second. So I'm going to say the name over here is the name I want to pass to this function. So I want to print out, in this case, I want to print a name. But I also want to print. And I want to specify some message in this case,
19:43
some message that's going to be passed in, let's say, plus. And I want to print the message in uppercase, maybe. So I would say dot to uppercase, so like this. So I could pass a message as a parameter. Let's start with that for a second. So I could say message. So in this case, if I call the greet, I could say hello.
20:04
And I could say Joe, for example. And I want this to print hello in uppercase and Joe. But we are passing an extra parameter hello in this case. But what if I really want to not pass the parameter, but that become implicit? So let's think about this for a second. What do we do in object-oriented programming?
20:21
We create objects. But what's the reason for creating objects? Sure, one reason is encapsulation. But there's another reason. We want a group of methods to be reusable. Well, if your goal is to reuse methods, wouldn't it be more reusable if you don't have objects, but you kind of walk up to arbitrary methods and say, hey, I like this method.
20:40
Can I reuse it, please? So in other words, in JavaScript, you can accrue methods and grab them and say, I want you to be part of my object. Can I use it with my object? And you can then call methods on the object directly. Let's take a look at how I can do that in this example. So I'm going to change this message. I'm going to remove this message from here. And I'm going to call toUpperCase.
21:02
But I'm going to call it on a special object called the this object. Now, of course, we don't know what the this object is. Where in the world did the this object come from? Well, this object is kind of special. So notice what I'm going to do now. I'm going to go to hello. So str equals, and I'm going to call hello over here.
21:22
And I'm going to then call greet. And I'm going to call the greet method with a call method, send the str as a first parameter, and hello as the, let's make this a name rather. So this is the message, right? So we'll send the message as John over here. So you can see that the message is hello.
21:41
And I'm calling the method greet with the message as a first parameter. And then I'm sending the object as a second parameter. So in this case, notice rather than just calling with the parentheses, I called a special method called the call method. When I call the call method, the first parameter is the implicit object on which
22:01
I'm going to call the method. In other words, think about this as a context object or a delegate object with which you're going to run this in. And whenever you call some method on this object, that this refers to the context object you sent to it. Similarly, I could have multiple parameters I can send to this. So for example, I could say name one comma name two
22:22
over here. And in this case, I would say name one plus. And then we could also say plus name two. And in this case, I could send Jack over here. And I could send Jill as a parameter. And you can see hello Jack Jill becomes the output. But the call method is convenient.
22:42
But there are times when you may be working in a web application and you get a collection of data on your hand. And if you have a collection of data, it's kind of silly to spend the time and effort taking this collection of object and unwrapping the collection into discrete parameters and sending them. That becomes pretty painful.
23:00
So what you could do instead is you could call greet. And you could call a method called the apply method. The word apply method comes from the functional style of coding where when you invoke a method, you're really applying the method. That's what you're really doing. So you're calling the greet and calling the apply method. And so in this particular case, you can still send the object.
23:21
But then you can send a collection of data for this guy where the collection is going to be Jack and Jill again. But notice in this case, I'm sending it as a collection rather than sending it as discrete parameters. And this becomes extremely powerful because now if I get an argument collection on my hand or a parameter list on a web application,
23:41
I can simply send that collection over. And then I can simply use it when I call the apply method. So we saw three different ways to call methods. You could simply call it with the parentheses. You can call it the call method. Or you can call it with the apply method as well. And those are three different ways to invoke this method. And you can use this flexibility to whatever you want it to.
24:00
And we also talked about the this parameter, which is an implicit object that you can call within the method. You can also use higher order functions very effectively in the case of JavaScript. And this becomes very useful for event handler purposes. You can register a piece of code and say, call me back when something interesting happens. And you can write these event handlers very easily
24:22
in the case of JavaScript. So for example, if you want to do that, you could pass a function or a callback into these functions. For example, let's say we have a function. And I want to call a callback into this. So I can say callback. And this could callback into this. So I could probably say foo called.
24:42
And then we can call into this callback at this time. I could say callback and send the parameter back to this guy. So we could say call the method foo, send a value five. And then I could write the function right here. So notice how the second way to define functions comes in handy here. Rather than assigning this to a variable,
25:02
you're just passing this function to this function as a parameter. So I could say p as a parameter. And I could simply define here u called width. And I could say the parameter p that you passed in. So that becomes the call here itself. So in this case, I could just call the function foo.
25:23
But I'm passing an anonymous function as a code block. This is a way to deal with higher order functions that you can just pass into these functions as a callback very easily. But the beauty in this particular case is I could really call this function as log it equals,
25:41
for example. And this could be just logging the value that you're passing in. So that becomes the function I want to pass to it. And then I can simply call this width log it as a parameter. And you will get the same output. So saving this as a variable and then reusing it in functions really makes it a lot more easier to work with.
26:01
As you can see in this particular case, it becomes very effective. So that is an example of using higher order functions for me to use in this particular case. So we looked at a bit of features of JavaScript, how to define functions, how to call functions, how to use implicit objects, how about arguments, collections, and stuff like that. Let's go back to something else, which is kind of weird in JavaScript.
26:22
And that is the comparative operator. And this is a bit of a pain, actually, in JavaScript. We've got to be a bit careful about this. So for example, if I were to call a function here, and well, actually, let's just do this. I want to print out, let's say, 2 equals 2.0. And notice in this case, it says it's a true.
26:43
Now obviously, in this case, we don't have a double quote around 2. It's not even a 2.0. What's really happening? One of the problems with the double equals is a double equals performs a comparison, but it transforms the object, converts the objects, before it performs a conversion.
27:01
And as a result, it may lead to some kind of a pain at some times, because it is not very, what do you call it? It's not symmetric operation. So if you switch parameters, it may not yield the same result. So the correct way to compare objects in JavaScript, in other words, in JavaScript, we rarely should use two equals.
27:20
It's a lot better to use three equals most of the time. Of course, if somebody asks you why, that is, you tell them three equals is way cool, then using two equals, right? So basically, the point really is that you really want an exact match, and not a match of comparison after conversion. And you can see that it gives you a false in this case, rather than being a true.
27:41
It becomes a bit more painful if you want to compare, for example, a not equals. So in this case, as you can see here, when you compare this, it says false, because it is equal with a two equals comparison. But if you really want to compare a not equals, once again, you may have to say a bang two equals to compare.
28:00
And so that's a bit of a painful syntax you have to keep in mind to verify that. So in other words, most of the time, you're going to use three equals in JavaScript, and a bang two equals in JavaScript, and never a two equals or a bang equals in JavaScript, or very rarely, rather. So just keep that in mind as you work through it. So that's all good so far, but it's time for us
28:22
to look at some object-oriented programming. I want to create an object. Well, notice I just said I want to create an object. Well, if you want to create an object, create an object. Why should you really worry about anything else? So it's kind of like your anonymous objects in C-sharp, right? In C-sharp, you used to create classes even
28:41
before you create any object. But today, you don't have to go through that trouble. If you really want just a single object, you can create an anonymous object. So in a very similar way, you can create an anonymous object in JavaScript. So I'm going to say here person equals, and I'm going to simply put a curly bracket,
29:00
and I'm going to say first colon, and I'm going to say Venkat, and then I'm going to say last colon. I'm going to put my last name here. And we created an object. We can print the object right here, and you can see that it created this object. You probably recognize the syntax. This is, of course, called the JSON object. Or if you are a person who likes to use accented words,
29:22
you can call it JSON object. But it's just a JSON object, right? So basically, this is just a very lightweight object you can create. One of the beauties of a JSON object is you can create this very easily. Its syntax is a subset of the JavaScript syntax. You can pass this to other libraries that can parse JSON object.
29:40
So web applications now can receive JSON objects, parse them, and use them. They can also generate or spit out JSON objects also very easily. But if this is an object, I can call properties on it. So I could say person dot first to get the first name. I could also say person dot last, and we could see the last name being printed.
30:01
But you argue, if it really is an object, I should be able to put functions on it also. So we could create a function called sync. No, not really. You don't want me to do that. Let's say hike. That's much safer, right? And you could call a function. You can assign the function, and then you can specify the mountain you want me to hike, and I would be glad to do that. And then I could say hiking, and we
30:22
could specify the mountain you want me to hike, and we could specify that. So you can see how you can put functions into these also very easily, for example. And of course, if you want to call this particular function, you can also call it very easily. And you can simply say person dot hike, and then you could specify whatever mountain
30:43
you want to hike. You can specify the mountain you want to hike, and that becomes very easy to work with. So creating objects is extremely simple, but you really want to create classes because that's what you really want to do in an object-oriented style of programming. So I'm going to say equals function,
31:00
and right there we created a class. There you go. That was very simple. You say, wait a second. You created a function, not a class. No, seriously, we created a class. How do you know you created a class? Well, pay attention. Notice how this was upper case letter, right? I know you're laughing right now. Absolutely.
31:21
That's exactly what JavaScript does also. It kind of laughs, a little chuckle. It's like these humans, they always need conventions. But it really is a convention. It's very helpful because for us, we want to know whether a class or a function is being created. So as a convention in JavaScript, if you're creating a class, use an upper case letter.
31:41
If you're creating a function, use a lower case letter. So that is a convention. It's purely a convention. But any time you create a function, you already created a class in JavaScript. So there's no ceremony associated with creating classes. That's a good news and a bad news in JavaScript. It's a good news because it's easy to create.
32:02
It's a bad news because it's not as simple as you create classes in Java or C Sharp. It takes just a little bit of an effort to do this. So you are wondering how this manifests itself. So if in this code, if I say, for example, a car called, and if I'm going to call this function car,
32:22
you would notice that it just calls it. In this particular case, we didn't really use this as a class for any particular purpose. But we can really put this to real good use as an object very easily. So in other words, if you think this is a class, think of this as more of a definition of a constructor
32:43
of the class, if you will. So if you look at it that way, I can say car 1 equals new car to create the object. And now if you notice, when I run this, it ran it like it runs a constructor of this particular class. So in other words, I used a new keyword
33:02
to instantiate this object. And what does it really mean when we do this? Now if you're asking for the type information, it becomes clear. So I could say type of, and in this case, I'm going to say car. And you notice that the type of car is a function. But if I say type of car 1 on the other hand,
33:23
you can notice it's a type of an object. So what's really happening in this particular case? What's really happening is when you do a new car, it creates an object, like a memo lock, if you will, from the C terms. It creates a memory for that object. And it instantiates a prototype for that object
33:43
and sets the prototype of this object pointing to a prototype that the car holds onto. So that's basically what's happened. Well, what is the so-called prototype? A prototype is a fairly interesting feature.
34:01
So think about what a prototype is. Think about it this way. I've got a little backpack. This is my favorite backpack. I carry it along with me all the time. Now if you come to me and say, can I borrow some rupees from you, dollars from you, Venkat, I would open my wallet. I'll grab some dollars and give it to you, because I've got it on me. But if you ask me, can I borrow some rupees from you,
34:23
I don't really carry rupees with me on my wallet, but I do travel to India quite a bit. And I have some rupees in my bag. I may reach into my bag. I will grab the rupees and I'll give it to you. So in other words, when you go to an object and ask for information, it really can look on itself to see if it's available.
34:42
If it's not available, it doesn't simply say no at this point. It goes on to its prototype. A little bag it carries with it and says, do you have this information for me? And if it does it, it collects that from there and gives it to you. But what's really interesting is, a prototype can have its own prototype,
35:01
which can have its own prototype, and this madness can continue for a long time until the very last one falls off the cliff and says, sorry, I can't help you. So in other words, it forms the object chain. Now this is, as it turns out, is an extremely powerful concept. It's worth spending some time learning about this,
35:20
and so we'll revisit this in a few minutes and come back to this. So we created an object so far, but I want to really say when this car was created, so I'm gonna pass an year as a parameter. So I'm gonna say that year is gonna be the parameter I receive into this object. But I have to store this parameter into my object to remember that, right?
35:41
So there's one more thing that's happening in this particular case. When you called new car, what really happened is the following. Think about it this way. Instance was created and pointed by car one, then call car dot call car one.
36:03
So notice the function call car, which I said is like a constructor, is being invoked with the context of car one as the parameter. So in other words, knowing that, you can now know how to set the parameter in this case.
36:22
So if I say, for example, car one dot year, it becomes undefined because we haven't defined it yet anywhere, but notice I'm gonna go back here and say this dot year equals the year, and that sets the parameter into the object. You can see how this comes to play right now. So in other words, you are saying
36:41
within the constructor, take this parameter you receive and set it as a member of this object in the context of this value that's being given to this guy. So that is basically what's being added to this. Now if I come to this particular class and say, this dot miles equals zero,
37:01
I can ask the car how many miles it's got, and you can see that it tells us the miles is zero, and now we can add a method, car dot drive. I'm gonna make a mistake here, and let's see what the mistake is and we can figure it out. So I say function is gonna be distance, and I'm gonna drive this car a certain distance,
37:21
so I'm gonna say driving, and driving is going to simply say the distance it's driving, and then I'm gonna say this dot miles plus equals the distance given. So all this is good so far, but I'm gonna call car one dot drive 10, and let's run this and notice it failed,
37:42
and the drive function really did not work on this object even though I wrote a drive on the car. Hmm, what do you think is happening? Why didn't that work?
38:01
So the reason for that is the drive function you added to the car itself, the car instance you created is just an object, but it's got a pointer to a prototype, right? That's all it has. The function drive was added to the car,
38:20
not to the prototype. What in the world is the prototype? Well the prototype is separate, so if I say car dot prototype dot drive, you can see that's working. So in other words, when you do a new car, the new car instance has a pointer to the car's prototype, and that becomes the holder of the object.
38:43
Now you can see one more thing from this example. Before I set this into the prototype that called failed, but after I set this into the prototype, it really worked really well. In other words, the object is able to acquire some behavior from the prototype dynamically at runtime.
39:02
Think of the beauty of this approach now. Now the object has a prototype, and multiple objects can have prototypes themselves. Each of them can have prototypes, but imagine for a minute, in the case of inheritance, how does inheritance work in Java or C sharp? You inherit from a class,
39:21
and all objects have that class as the base class, end of story. But imagine the possibility when you can modify your inheritance at runtime. For example, I've got the most wonderful parents in the world. They taught me real good values, and I inherit a lot of value from my mom and dad.
39:40
But I wouldn't mind an option where I will have my dad and mom during the weekdays when I go to school or when I go to work and they discipline me, teach me good stuff. But in the weekends alone, I get rich parents, however, that, right? So I can flip my inheritance and say, in the weekends, I'll have rich parents who will take me around, I can do all the fun stuff,
40:00
and then flip back during the weekdays and I can have my own parents who can teach me the values in life, right? So in other words, imagine you are taking an object you're running it in a context, but you want to do a certain amount of tests on the object. It'd be so cool to mock away the behavior. Well, don't worry about it. Simply take this object and say,
40:21
hey you, rather than your prototype pointing to this object, flip your prototype to this mock object, which can mock away your environment completely. You don't have to change this object at all. You can very easily now have this object work on a mock environment, and when you're done, you can flip back to the original object,
40:41
and you're back to where you want to be. Now this is interesting concept, but also leads to one concern. How does this really work under the covers? When you have a class, you can create multiple objects of this class, and all these objects share the same prototype. You say, wait a second, what's good about sharing the prototype?
41:02
It's better on memory usage, it's easier to create them, but sharing could be a problem, however, remember. Why, because if you change an object, then you don't want the other object to be seeing the change, because that would confuse the heck out of your system. How does this really work? To understand this, we'll take a little example here.
41:20
Now there are two things you do on an object. You get properties from objects, and you set properties on objects. I'm gonna use Thomas' help here to achieve this particular goal. So Thomas I know is a rich guy here, he can help me quite a bit. So he is my prototype, I'm pointing to him. Now you come to me and say, hey Venkat, can I borrow $10 from you?
41:42
Sure, I can open my wallet, I can grab $10 to you, I give it to you and say, here you go. A week goes by, you come along and say, hey Venkat, thanks for the $10 you gave me, you were such a help, here you go, and you give me back my $10, and I take my $10 and I put it in my pocket. Life is good, right? So a week goes by, and you come to me and say,
42:01
hey, can I borrow 2,000 Kronos from you, please? I'm not gonna say no to you. I look around and guess what? I don't have any Kronos on me. So what am I gonna do? There you go. I forward my request to him, and he picks up his Kronos for me, being such a nice guy,
42:21
and he gives it to me, right? Oh, credit card, no, no, I want the real money, the real green cash. So he gives me the money, and I give it to you. Worked so far, right? So you got the money. A week goes by, you see me again, you say, thank you so much Venkat for giving me the Kronos and a timely help. Here is the Kronos back to you. I received the Kronos from you.
42:42
What am I gonna do with it? Oh, no, I'm gonna put it in my pocket, right? And that is exactly what JavaScript does, right? So JavaScript takes the credit. Venkat was such a great help, right?
43:00
But who gave me the real money? Thomas did. But will it ever go back to him? No, of course not. If you understand this model, you understood exactly what JavaScript does. Now why does JavaScript do this? Think about this for a minute. If two objects share the same prototype, when you do a get, if neither of these objects have a property,
43:22
they both get the value from the prototypal inheritance, kind of giving you the inheritance behavior. You come to one object and modify the data. If this were to set the data in the prototype, then you go to the other object and ask for the data, you'll be confused.
43:41
How in the world did it change the data? I never touched it. So in other words, in JavaScript, gets are deeper, sets are shallow. Let's take a look at an example here real quick. So notice for a minute here that I have a vehicle I'm gonna create. So I say var vehicle,
44:01
and this is gonna be a function, and this is gonna take miles as a parameter. So this dot miles equals zero. So I've set the miles on the object right there. So now I'm gonna say here, the drive method is actually part of the vehicle itself. So let's go ahead and say vehicle dot drive.
44:22
So that becomes part of the vehicle itself. And now I come back here to the car, and I say car dot prototype equals new vehicle. So I have a vehicle as a prototype for the car itself. So I come to the car, I create a car object,
44:40
I call the drive method on the object, it prints it. I say car two equals new car, let's say 2012 also. And in this case, I say print line car two dot miles value. And notice in this particular case, I'm creating an instance of car two,
45:00
let's see what I did wrong here. So I created a car object, oh there we go. So I say car two dot miles to get the values of the miles, and notice it's a zero, not a 10. And the reason is, if I say car two dot drive, and say 20 now, and I say print line car two dot miles
45:22
again over here, you can see it's a 20, but if I say car one dot miles, you can see it is still at a value of 10. So even though the prototype is shared, they both have a value of zero to begin with, notice the value is different after a while. How does this really work?
45:40
Let's look at an example to understand this a little bit further. So let's go back to this code and say, I've got a car one on hand, and I'm gonna say for property in car one, and I'm gonna simply print the properties of the car itself. You can notice that it tells us that it contains the properties,
46:02
I'm gonna remove this for a second so we can reduce the output. So it says there is a year, miles, and drive. But you can ask him one more question. You can ask him is plus, and we could also specify, and I could say a car one dot has own property,
46:22
and I can tell him the property itself, and that tells me whether the property is his own property or not. So has own property is the function I'm gonna use. So has own property, this is gonna be car rather, so car one, there we go. So you can ask him if it is own property. So he tells me year is his own property,
46:43
miles is true it says, drive is false, it's not his own property in this case. Now let's go back here for a second, and let's remove all this for a second. Let's just focus on the car itself for a minute, and let's remove this also for a second. Well actually let's leave that for a minute.
47:01
Let's come back to calling this. So we are asking for, this one here, so reduce all the code. So it tells me miles is his own property, right? How did it know it's his own property? Because we set the miles to this. But on the other hand, if I were to say a prototype for this guy, so let's remove this from here for a second,
47:21
and we will say car equals car.prototype equals, and I'm gonna simply create miles as a value within this and I'm gonna set this here, because after all a prototype could be any object, isn't it? So I just created a prototype, set the miles on him, and I said to the car, hey car, go ahead and tell me what your properties are.
47:43
It says year is his own property, but miles is not. But miles is still a property, but it's not his property, it's from the prototype. But on the other hand, I go back to the car itself and say car one dot miles equals seven, and now I print car over here.
48:00
I can ask him car one dot miles, and notice in this case it prints a seven. Now I ask him for a reevaluation of properties and notice the difference. Now it says miles is part of the object itself, not of the prototype. And the reason is, when you call for a property,
48:22
the get goes to the prototype if you don't have it. In other words, gets are deeper. On the other hand, a set is shallow. You come to me and give me money, I keep it. Sorry, Thomas, right? So that is basically what you're doing, is you are keeping the sets locally at the first level of object, whereas the gets are deeper.
48:41
So this creates a nice concept of inheritance using prototype, please. That's correct. So on line number five, we replace the entire prototype. So that is something you gotta be very careful about when it comes to JavaScript,
49:01
because you can easily change the prototype, and that's good in some cases, bad in other cases. So you gotta be very careful about it. If you don't want to remove the prototype, then you can go add a property to it also. You could do that as well. So that's perfectly fine. Yes, in this case I just removed the prototype and replaced it, absolutely, you're correct. That brings the question,
49:21
there's something else you can do very nicely in the case of JavaScript. You can define on the prototype some functions, for example, drive, and I'm gonna give a distance over here, and we can see drive called, so I could say drive called. So right there, and then we could say this dot miles plus equals distance,
49:40
and we could set the distance itself, miles equals zero. So let's start with this for a second. So I created an object of car, and car one dot drive, and I could say 10 over here, and you can call the functions over here. So this is function, equal to function. There we go. So you can call the drive function. You can call on the car, car one dot miles,
50:03
and it tells you the miles value. Whatever the miles value was, it tells you that. So you could do that. But here is something my car can do, I bet your car cannot do. So var Venkatescar. Venkatescar is special. New car, and was created a long time ago, and you know where I'm going with this.
50:22
So you can say Venkatescar dot drive a mile. Don't push it too hard, right? It drives a mile. You can ask Venkatescar's miles value. It tells you what the miles value is. But my car is special, like I said. And I can say Venkatescar dot breakdown equals function,
50:43
and I can call a breakdown function on this, right? So broke down, like it normally does. And I can come to Venkatescar and say breakdown over here. And you can see that this function actually can be called on this object itself.
51:00
So Venkatescar breakdown is a function I'm creating. Let's make sure I've said this properly. So in this case, I'm going to say Venkatescar dot breakdown, and I'm calling this function. What am I doing wrong here? So this is Venkatescar, right? Oh, breakdown is the function name, right?
51:20
So that's perfectly fine. I'm just defining the function. Oh, did I do that? Thank you. Yeah, you're right. Thank you. So right there, that broke down, as you can see. OK, so you can call the breakdown. But what if I do this? Try, and we could say catch exception, so we can see the exception.
51:41
We'll print out the exception we received. And in this case, I'm going to say car one dot breakdown over here. You can see that in this case, it has no method. So in other words, you can add functions to single objects, or you can add functions to the entire class of objects as you please.
52:01
That gives you a fairly decent flexibility. So in that regard, mocking becomes extremely trivial in the case of JavaScript, and you can easily mock away certain objects very easily. I showed you how to examine properties. I showed you how to get properties, and check if it's a property of the object itself. How do you call the properties on objects?
52:21
So you can see how easy it is to call properties. You're able to call miles just like that directly. But there are times when you may be in an application where you don't want to hard code variable names. So I would say var name equals, and this may come as an input from a web form or something, for example.
52:41
So you can simply say, in this case, you can print car and say car1, square bracket, var name, and you can simply pass the variable name as a parameter. Similarly, you can invoke functions on the object also by specifying a square bracket, and put a parentheses around it, and you can invoke methods on it very easily
53:02
in this particular case. So this brings up one question. If we can do all of this, well, you can also delete properties, but I don't recommend it. You added instance level properties. You can also create classes, but we talked about prototypal inheritance, but let's talk about inheritance in the true sense for a minute.
53:20
So if I were to create a vehicle class over here, where the vehicle has, let's say, a drive function, so this is another way you can define it. Within the function, I have a distance, and I'm going to simply say call this and say driving, and then let's print out this dot, miles plus equals the distance.
53:42
So this dot miles equals zero to begin with. So I want to create a car over here, and the car has a year, but I'm going to set the car's prototype, in this case, as a new vehicle, right? So far, so good. Now, I can then say something like this.
54:00
I could say car1 equals new car, and I could call the drive method, so drive10. We could call this, and you can see it says driving. Let's put vehicle driving here for a second, but remember the prototypal nature of this. So I could go to the car itself, and in the car, I'm going to say this dot drive
54:25
over here, and equals function. Going to take a distance, and I'm going to say here a car driving. So notice in this case, it only calls the car driving, and the reason is, when you go to the object,
54:41
the prototype has the drive method. The instance has the drive method in its own prototype also, right? So in this case, this is hiding the method from the prototype, and that's what you're seeing in this particular case. But I really want to get back to the method of the original class. How do I do that? In terms of that, you want something like super, right?
55:00
Because that's how you go back to inheritance model. But unfortunately, how do you reach into the object? There are a couple of things you could do. One thing you could do is to get to the object's prototype itself. So for example, you could say this dot, a proto, and ask for the prototype of the object. So that gives you input into the prototype of the object.
55:23
Or alternately, what you could do is you can also just say vehicle dot and call it. But let's assume for a minute we want to go this route. So this dot, proto. So you could say proto, and then dot drive. But you want to call the drive method. But remember, you want the drive method
55:40
to run in the context of the current object. So you would say dot call, and you would pass the this, and then pass the year parameter to it. And you can see how you're able to reach into the base object. You could either do that, or you could call apply method, and then simply send the arguments that you received in your own object over here.
56:02
And that can be another way to pass that also to the base class. So we're able to reapply some of the things we learned along the way. And you can kind of bring back the overriding concept. And from your method, you can call into the overridden method. From the overridden method, you can call the method that you're overriding into the base class as well.
56:20
So that supports a very exciting way to reach in. Our last few words, arrays, really, are a bit weird. They really are arrays wannabe. There are a few problems with it. The indices of the arrays, really, are their properties. And then there's values associated with them. Be careful. You can delete properties, but unfortunately, that can leave holes in the object.
56:42
I talked about exception handling just a little bit. You can take a look at it. But as you saw, there are several ways to do things in JavaScript. You could get things done really wrong in a number of ways. If you really want to keep a handle on how you write code with JavaScript, Douglas Crockford has written a tool called JSLint.
57:01
And JSLint is a really good tool, but I recommend you sit down before you use the tool, because it really can hurt your feelings. And if you give them a JavaScript, I've never written a JavaScript that JSLint doesn't complain about. And the minute you give a code to JSLint,
57:21
it'll give you a slap first. And you've got to emotionally handle that kind of things. And it was so painful to one guy, he went on to create another tool called JSHint. JSHint also slaps you, but gives you a hug afterwards. So it's just a little bit better tool than JSLint itself. But JSLint will complain about a lot of things.
57:41
It's a good idea to run your code through JSLint. But if you really don't want to go through that, unfortunately, I won't talk about it here in my talk, but I want to just kind of leave that with you, is a better way to write JavaScript today is to write CoffeeScript. And CoffeeScript actually is a language that removes a lot of these burdens from JavaScript.
58:01
You may say, wait a second, if I really should be using CoffeeScript, why should I really learn JavaScript? Well, the reason is simple. Any time you deal with something, you have to know at least one level below the level of abstraction. And if you're going to use CoffeeScript, you still have to look at JavaScript when you debug your code or take a peek into it. And also, if you're looking at tools like jQuery,
58:22
it becomes a lot more easier to understand and appreciate what's being done if you do understand JavaScript. I really hope you got something out of this session. Thank you for your time.
Empfehlungen
Serie mit 110 Medien
Serie mit 96 Medien
Serie mit 163 Medien
Serie mit 170 Medien
Serie mit 150 Medien