[Native JS] Front-End development must be mastered by seven JavaScript skills __ Big Data

Source: Internet
Author: User
You may be frustrated if you are a beginner of JavaScript or have only recently contacted it in your development work. All languages have their quirks (quirks)-but developers who move from a strong-typed server-side language can be confused. I've done this before, a few years ago, when I was pushed to a full-time JavaScript developer, there were a lot of things I wanted to know from the start. In this article, I'm going to share some quirks and hopefully I can share some of the experiences that have given me a headache. This is not a complete list--just a part--but hopefully it will give you an insight into the strength of the language that might have been something you thought was a hindrance.
We will look at the following tips:
Equality Dot vs Bracket function context function declaration vs function expression naming vs anonymous function immediate execution function expression typeof vs Object.prototype.toString


1.) Equal
C # I was very familiar with the = = comparison operator. Value types (or strings) are equal if they have the same value. Reference type equality needs to have the same reference. (Let's say you don't overload the = = operator, or implement your own equivalent operation and GetHashCode method) I'm surprised why JavaScript has two equivalent operators: = = and = =. Most of my code was originally used for = =, so I didn't know what JavaScript did for me when I ran the following code:
var x = 1;

if (x = = "1") {
Console.log ("yay! They ' re equal! ');
Copy Code

Is this dark magic? How the integer 1 is equal to the string "1".

In JavaScript, there is equal (= =) and strict equality (= =) said. The equality operator performs strict equality comparisons after casting the operands on both sides as the same type. So in the above example, the string "1" is converted to an integer 1, which is done behind the scenes and then compared to the variable x.

Strict equality does not convert to type. If the operand types are different (such as integers and strings), they are not congruent (strictly equal).
var x = 1;

Strictly equal, the type must be the same
if (x = = "1") {
Console.log ("Sadly, I ' ll never write this to the console");
}

if (x = = 1) {
Console.log ("yes! Strict equality FTW. ")
Copy Code

You may be considering the various horrors that might arise from coercion of type conversions--assuming that this conversion occurs in your reference, it can be very difficult to find out where the problem is. That's not surprising, and that's why seasoned JavaScript developers always recommend using strict equality.

2.) Dot vs Bracket
It depends on what language you come from, you may have seen it or haven't seen it (that's nonsense).
Gets the FirstName value of the Person object
var name = Person.firstname;

Gets the third element of the array
var theonewewant = myarray[2]; Remember, 0-based index don't forget the first element is indexed with 0 copy code

However, you know it can also use parentheses to refer to the members of an object. For example:
var name = person["FirstName"]; Copy Code

Why is it so useful? And you will use the dot notation most of the time, there are several instances of parentheses so that some methods may not be able to do so. For example, I would often refactor large switch statements to a dispatch table, so things like this:

Why it can be used this way. You may have been more familiar with the point of use, and there are several exceptions that can only be expressed in parentheses. For example, I often refactor a switch statement to a lookup table (faster), in fact, like this:
var dosomething = function (dowhat) {
Switch (dowhat) {
Case "dothisthing":
More code ...
Break
Case "dothatthing":
More code ...
Break
Case "dothisotherthing":
More code ....
Break
Additional cases here, etc.
Default
Default behavior
Break
}
Copy Code

can be transformed into something like the following:
var Thingswecando = {
Dothisthing:function () {/* behavior */},
Dothatthing:function () {/* behavior */},
Dothisotherthing:function () {/* behavior */},
Default:function () {/* behavior */}
};

var dosomething = function (dowhat) {
var Thingtodo = Thingswecando.hasownproperty (dowhat)? Dowhat: "Default"
Thingswecando[thingtodo] ();
Copy Code

There are no errors with the switch (and in many cases, the switch may be better than the lookup table if it is iterated several times and pays great attention to performance). However, look-up tables provide a good way to organize and extend your code, and parentheses allow you to evaluate property latency.

3.) function context
There have been some great blogs that have published articles that correctly understand the this context in JavaScript (I'll give some good links at the end of the article), but it really should be added to the "I Want Me to Know" list. It's really hard to read the code and confidently know the value of this in any location--you just need to learn a set of rules. Unfortunately, many of the explanations I read early in the morning just added to my confusion. So I tried to explain it succinctly and concisely.

First-Consider the overall situation first (global)
By default, this value points to the global object, until some reason has changed the execution context. In the browser, that will be the Window object (or Global in node.js).

Second--The This value in the method
When you have an object that has a function member that invokes this method with the parent object, this value will point to the parent object. For example:
var Marty = {
FirstName: "Marty",
LastName: "McFly",
Timetravel:function (year) {
Console.log (This.firstname + "" + This.lastname + "is time traveling to" + year);
}
}

Marty.timetravel (1955);
Marty McFly is time traveling to 1955 copy code

You may already know that you can refer to the Marty object's Timetravel method and create a new reference to another object. This is actually a very powerful feature of JavaScript--enabling us to refer to behavior (call functions) on different instances.
var doc = {
FirstName: "Emmett",
LastName: "Brown",
}

Doc.timetravel = Marty.timetravel; Copy Code

So--what happens if we call Doc.timetravel (1885).
Doc.timetravel (1885);
Emmett Brown is time traveling to 1885 copy code

Once again--the dark magic is staged. Well, it's not true. Remember, when you call a method, the this context is the parent of the called function parent.

When we save Marty. Timetravel the reference to the method and then calls what happens when we save the reference. Let's see:
var getbackintime = Marty.timetravel;
Getbackintime (2014);
Undefined undefined is time traveling to 2014
Why is "undefined undefined". Rather than "Matry McFly". Copy Code

Let's ask a key question: What is the parent object/container object when we call our Getbackintime function. When the Getbackinttime function exists in the window, we call it as a function, not as a method of an object. When we call a function like this--no container object--this context will be a global object. David Shariff has a great description about this:

Whenever we call a function, we must immediately look at the left side of the bracket. If there is a reference to the left of the parentheses, the this value that is passed a calling function is determined to be the object to which the reference belongs, otherwise it is an absolute object.

Since the this context of Getbackintime is window--without FirstName and LastName attributes-This explains why we see "undefined undefined".

So we know to call a function directly--the result of no container object--this context is the global object. However, I also said that I knew that our getbackintime function existed on the window. How I knew it. Well, unlike the above I wrap getbackintime in different contexts (when we explore the immediate execution of function expressions), I declare any variables that are added to the window. Verification from the Chrome console:



It's time to discuss one of the main strengths of this: Subscribe to event handling.

Third (just the extension of the calculation)--calling the this value in the method asynchronously
So let's pretend we want to call our Marty.timetravel method when someone clicks a button:
var flux = document.getElementById ("Flux-capacitor");
Flux.addeventlistener ("click", Marty.timetravel); Copy Code

In the above code, when the user clicks on the button, we see "Undefined undefined is time traveling to [object MouseEvent]". What the. Well--First of all, the obvious problem is that we haven't given the year parameter to our Timetravel method. Instead, we subscribe directly to this method as an event handler, and the MouseEvent parameter is passed as the first argument to an event handler. It's easy to fix, but the real problem is that we see "undefined undefined" again. Don't be hopeless-you already know why this happens (even if you don't realize it). Let's modify our Timetravel function and output this to help us figure out the facts:
Marty.timetravel = function (year) {
Console.log (This.firstname + "" + This.lastname + "is time traveling to" + year);
Console.log (this);
}; Copy Code

Now-When we click on this button, we will resemble the following output in your browser console:



When the method is invoked, the second Console.log outputs the this context-it is actually the button element that we subscribe to the event. Do you feel surprised. Just like before--when we assign Marty.timetravel to a getbackintime variable--the reference to Marty.timetravel is saved to the event handler and called, but the container object is no longer a Marty object. In this case, it will be invoked asynchronously in the Click event of the button instance.

So--it's possible to set this to the result we want. Absolutely can. In this case, the solution is very simple. Instead of directly subscribing to Marty.timetravel in an event handler, you use an anonymous function as an event handler and call Marty.timetravel in an anonymous function. This also fixes the problem of year parameter loss.
Flux.addeventlistener ("click", Function (e) {
Marty.timetravel (Someyearvalue);
}); Copy Code

Clicking the button will output information similar to the following in the console:



It worked. But why is that possible? Think about how we call the Timetravel method. In the first example of our button clicks, we subscribe to the reference of the method itself in an event handler, so it is not invoked from the parent object Marty. In the second example, through this is the anonymous function of the button element, and when we call Marty.timetravel, we call from its parent object Marty, so this is Marty.

Four--the this value in the constructor
When you create an object instance with a constructor, the this value inside the function is the newly created object. For example:
var timetraveler = function (FName, lName) {
This.firstname = FName;
This.lastname = LName;
constructor functions return the
Newly created object for us unless
We specifically return something else
};

var marty = new Timetraveler ("Marty", "McFly");
Console.log (Marty.firstname + "" + marty.lastname);
Marty McFly
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.