知识点18:JavaScript

So how do we include JavaScript in our html to start with?


Syntax:

So JavaScript variables, we'll start talking about the syntax here. And we'll go through this kind of quickly, because we've done this in PHP, so this should all be pretty familiar.

What about functions in JavaScript?


Arrays in JavaScript are pretty straightforward.

To declare an array, you use the square brackets syntax that we're familiar with from PHP. And similar to PHP, we also can mix data types.

So this array, both of these arrays would be perfectly legitimate JavaScript. One that's all integers, and one that is mixed up different data types.

But what is an object, what is this notion of an object?

If I define a structure for a car like this with the following two fields or properties, one an integer for the year of the car and another a 10 character string for the model of the car, I can say something like this, I can declare a new variable of type struct car herbie.

And then I can say something like herbie.year equals 1,963, and herbie.model equals Beetle.

That's OK.

I'm using the fields in the context of the structure, but I could never just say something like this.

Right?

I can't use the field name independent of the structure. It's sort of a fundamental thing.

So fields being fundamental to C structures are very similar to properties being fundamental to JavaScript objects.

But what makes them particularly interesting is that objects can also have what are called methods, which are really just a fancy word for functions that are inherent to the object as well.

So it's a function that can only be called in the context of an object. Only an object that has defined this function inside of its, if you think about a struct, the function is defined inside those defining curly braces of the structure.

So it only means something to the structure. And that's sort of what we're doing here with objects and methods. It's basically like we're defining a function that only makes sense on a particular object, and so we call that a method of the object. And we can never call that function independent of the object, just like we can't say year or model independent of the struct in C.

So functional programming paradigms look something like this. Function and then when you pass in the object as a parameter.

In an object oriented programming languages, this sort of gets flipped, and we would think about it like this, object.function.

So it sort of that dot operator again implying that it's some sort of property or attribute of the object itself.

But this is what an object oriented programming language might do to make a function call on a method, again, which is just a special word for a function that is inherent to an object.

This is what that syntax might look like. And so we'll start to see some of this in the context of JavaScript.

You can also think about an object sort of like an associative array, which we're familiar with from PHP.

Remember an associative array allows us to have key value pairs, instead of having indexes 0, one, two, three, and so on like we'reused to from C arrays.

Associative arrays can map words, such as in the PHP video, we were talking about toppings of pizzas. And so we had an array called pizzas, and we had cheese was a key and $8.99 was the value, and then pepperoni was a key, $9.99 was a value, and so on.

And so we can also think about an object sort of similar to an associative array. And so this syntax here would create a new object called herbie with two properties inside of it.

And notice here that I'm using single quotes in JavaScript.

You can use single or double quotes when you're talking about strings. It's just conventionally the case that most times when you're writing JavaScript, you just use single quotes.

But I could use double quotes here, and that would be perfectly fine as well.


So remember how in PHP we had this notion of a for each loop that would allow us to iterate over all of the key value pairs of an associative array, because we didn't have this ability to iterate through 0, one, two, three, four, and so on.

PHP syntax

JavaScript has something very similar, but it's not called a for each loop, it's called a for in loops.

So if I said to me like this, for var key in object, that's sort of similar to saying for each something as something.

But all I'm doing here is iterating through all of the keys of my object. And inside of the curly braces there, I would use object square brackets key to refer to the value at that key location.

Alternatively, there's even another approach. If I just only care about the values, I can say for key of object, and just use key inside.

So for var key in object, I have to use object square brackets key inside the loop.

For var key of object, I can just use key inside the loop, because I'm just specifically talking about the values there.

So let's maybe take a look at the difference just to quickly show you the difference between for in and for of with a very specific array, which we have here, week array.

I want to now iterate through this array, printing out certain information.

If I use a for in loop to print out information, what do you think I'm going to get?

Well, let's take a look.And before we jump over to my browser window, just know that console.log is sort of one way of doing a print F in JavaScript.

对console的解释:

But what is the console? Well, that's what we're going to go take a look at right now.

OK, so we're back here in my browser window, and I'm going to open up my developer tools. Again, I'm just hitting F12 to open up developer tools. And notice that here at the top I've chosen console.

So this is the notion of a developer console, and it will allow us to print information out, sort of like the terminal, but as you'll see a little later, we can also type information in to interact with our web page. I'm going to zoom in a little bit here, and I'm gonna now click on for in test. And four in test-- I'm not gonna show you the code for it right now, but you'll get it if you download the source code that is associated with this video-- is just that for in loop that we saw just a second ago on the slide.

So I'm gonna click that button, and over here, here's what has printed out in the console, 0,one, two, three, four, five, six.

I didn't print out the information inside those array locations, because I used a for in loop. And inside the body of the loop, I just printed out key not object key.

But if I now clear my console, and I switch to for of test, and four of test I say I use for of loop instead and print out key, if I click that, now I'm getting the actual elements inside of my object or my array in this case.

My array of week days. I printed out Monday, Tuesday, Wednesday. So that's the difference between a for in loop, which prints out just the keys if you just use key inside of the body of the loop, and a for of loop, which prints out the values if you use just key inside the body of the loop.

「总结就是:

for in的情况下, 打印键key,

for of的情况下,就打印值value」


All right, how do we now start to concatenate strings and maybe mix up some variables with interpolation like we were able to do in PHP?

Well, we're pretty familiar with this from PHP.

In JavaScript, though, we actually use something called the plus operator, which is maybe even a little bit more intuitive, right?

We're adding a bunch of strings together. So let's head back over and see what this will print if we're trying to print out all of the information in week array. All right, so under here under string concatenation, I have two options, string building V1 and then string building V2.

And we'll see why we need V2 in a second. But I'm gonna click on string building V1, which is the code we were just taking a look at, the console.log with all of the pluses.

Let's see if this prints out what we expect.

Well, what I was trying to do there was get it to print out Monday is day number one, Tuesday is day number two. But it seems like I'm always printing out one.

Well, why is that?

Well, it turns out, take another look at this little snippet of code here.

Notice that we're using the plus operator in two different contexts. And so here's where maybe things that we've kind of been saying,

oh, it's so great. We don't deal with data types anymore. But here's where the fact that we lose data types can actually be a bit of a problem for us. Now that the plus operator is used to concatenate strings and add numbers together, JavaScript has to make its best guess as to what I want it to do for me.

And in this case, it guessed wrong. It just concatenated day, which would be 0, one, two, three, four, five, or six, and then it just concatenated that and then concatenated one. It didn't actually add them together.

And so these languages, PHP and JavaScript, that abstracts away this notion of types, you don't have to deal with it anymore.

They do still have types under the hood. And we can, in situations like this, leverage that fact by saying something like maybe this,

which is telling JavaScript, by the way, treat this as an integer, don't treat it as a string, even though we're mixing together strings and integers here.

It's just one of those things that it seems so great in context that we don't have to deal with types anymore, but sometimes you'll run into a situation exactly like this where the fact that you don't have control over types can backfire on you if you're not careful.

And so if we pop back over to IDE, I'm going to clear out my console again, and I'm going to click string building version two, which is where I use that parse int function. Now it's printing out information that I'm expecting. Monday's day number one, Tuesday is day number two, and so on.


So let's talk about functions again. I promised we would talk about anonymous functions, and now the context for that has finally arrived.

So before we do so, let's talk again about arrays for just a second.

There's a method called size, array.size, which will return to you as you might expect the number of elements in your array.

array.pop, sort of like our notion of popping off of a stack, if you recall from our stacks video, removes the last element from the array.

array.push adds a new element to the end of an array. array.shift is sort of like DQ, it splices out the very first element of an array.

a mapping function. In the context we're talking about here, a map is a special operation we can perform on an array to apply a particular function to every element of that array.

so we would say in this case, maybe array.map, and inside of it, we're passing into map is a function that we want to be applied to every single element.

So it's sort of analogous to using a loop to iterate over every element and apply a particular function to every element ,just JavaScript has this built in notion of a mapping that can be applied.

And this is a great context to talk about an anonymous function.

So let's say we have this array of integers.

It's called nums, and it's got five things in it, one, two, three, four, five.

Now I want to map some function on to this array. I want to have a function apply to every element of the array.

Well, let's say that what I want to do is just double all of the elements.

What I could do is just use a loop for var I equals 0, I is less than or equal to 4, I plus, plus, and then double every single number.

But I can also do something like this.

I can say nums was formerly one, two, three, four, five, now, though, I would like you to apply a mapping onto this array where I would like you to double every number. And that's exactly what's happening here. But notice what I'm passing in as the argument to map.

This is an anonymous function. And notice I haven't given this function a name, I've only given it a parameter list.

And so this is an example of an anonymous function.

We generally would never call this function outside of the context of map. We're defining it as a parameter to map, and so we don't really need to have a name for it if the only thing that cares about is map and it's defined right there inside of map. And so this is an anonymous function. We have not been able to do this previously.

Map some function that accepts one parameter, num, and what that function does is returns num times 2. And so after this mapping has been applied, this is now what nums looks like,

two, four, six, eight, 10.

And we'll pop over to my browser window and just take a look at this really quickly as well.

So I have another button here in my home page called double. And when I click double, and it tells me before it was one, two, three, four, five after two, four, six, eight, 10. And if I go back and click double again, two, four, six, eight, 10. And then after, four, eight, 12, 16, and then 20.

And what am I doing in this function?
Well, if we just pop over to IDE, and I pull up my anonymous function, here

on line seven through 13, I'm doing a little bit fancy work here, but I'm just printing out what's currently in the array.

Then on line 16, 17, and 18, there's my map. This is where I'm applying this doubling function to every single element.

And then a little further down,

I'm just doing the same thing I was doing before, except now I'm printing out the contents of the array afterwards.

But all I've done here is just use an anonymous function to map across an entire array.


So one more big topic to talk about in JavaScript is the notion of an event.

An event is something that just happens when a user interacts with your web page, so maybe they click something, or maybe the page is finished loading, or maybe they've moved their mouse over something, or they've typed something in an input field.

All of these things are events that are occurring on our web page. And JavaScript has the capability to support something called an event handler, which is a callback function that responds to an html event.

And what's a callback function?

Well, it's generally just another name for an anonymous function.

It's a function that responds to an event. And this is where we come to the idea of binding certain functions to a particular html attribute.

Most html elements have support for an attribute that we didn't talk about in the html video for something like on click or on hover or on load, all of these events that you can then write functions that deal with those events when those events occur on your web page.

e.g:

And so maybe your html looks something like this.

And I have two buttons here, button one and button two, and here I have currently defined nothing, but this is where the attribute on click is apparently part of my html tag. So apparently when I define what's going on inside of that attribute,

it's going to be some JavaScript function(就是上上那张黑色背景的图,alertdate()就是一个JS函数) that responds to the event presumably of clicking on button one or button two.

What's kind of cool about this is we can write a generic event handler.

And this event Handler will create an event object. And the event object will tell us which of the two buttons was clicked.

Now how does that work?

Well, it might look something like this. So we will first define our buttons to have a response to the callback function that will be called when the button is clicked, we'll call event alert name.

And notice in both cases we're passing in this event parameter. So we call this function or when this function is triggered by the event happening, it's going to create this event object and pass it as a parameter to alert name.

And that event object is going to contain information about which button was clicked.

And how does it do that?

Well, it might look something like this.

So now in my separate JavaScript file, I might have to find this function alert name, which again accepts that event parameter.

And then here is where I'm detecting which button was triggered,

What was the source that created this event object that was passed in?(被传入的这个事件对象的资源又来自哪里?)

Was it button one or was it button two?

And then here:

all I'm doing is printing out trigger.innerhtml.

Well, in this case, in this context, trigger.innerhtml is just what is written on the button.

(在这个案例里,则是button1和button2:

It just so happens if we jump back for a second,

that would be what's in between those button tags. It will be button one or button two. And let's take a look at how this event handler would look if we had it running in practice.

So first of all, you've opened up events.js, which is the JavaScript file where I have defined this function. And as you can see, it's pretty much exactly what we just saw on the slide a second ago.

And I will go over to the home page we've been using. And I have here button one and button two. And I'll click on button one. You clicked on button one, if you can see right here in the alert. OK. Click on button two, you clicked on a button two.

So both buttons have the same function call, right?

They both were alert name event, but this event object that gets created when we click on it tells us which button was clicked.

We didn't have to write two separate functions or deal with having to pass any additional information. We're just relying on what JavaScript will do for us, which is to create that sort of event object on our behalf.


There's a lot more to JavaScript than what we've covered in this video, but having these fundamental should get you quite a long ways to learning everything you'll need to know about this interesting language.

The End

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容