JavaScript fundamental Concept

Source: Internet
Author: User
Tags string methods

The function:function itself is an object that can be assigned to any variable

Immediate invoked function expression (Iife): function () {} ()

Method vs Function: A method is a function attribute of an object (the A method is a function, which is a property of an object) for example:

var console={

Log:function () {}

}

Console.log ("Log is the method! of the console");

String methods:

The following method or property is a method or property defined by a string Object!

Length: This length is actually a property, not a method.

IndexOf

var line = "hal:i ' m Sorry, Dave. I ' m afraid I can ' t do '; alert (Line.indexof (//  5//   )

slice,substr,substring function:

var greeting = "Hello, Andrew, what's up?"  = Greeting.slice (7,+//  Andrew

Split: This function separates each word into an array by using a character string as a partition

var arr = "apples oranges Peaches Bananas". Split (""//  ["Apples", "oranges", "Peaches",? /c3> "Bananas"]

toLowerCase, toUpperCase

Date Methods

Date object has a number of useful methods to use

Getdate,getday,getfullyear,gethours,getmilliseconds,getminutes,getmonth,getseconds,gettime,gettimezoneoffset

Setdate,setfullyear,setminute,setmonth,setseconds,settime,setmilliseconds,sethours,

Parse: Can be used to tell a string to parse to date object

// 14529600000 // 1289451600000 var New // Tue APR? 1995 00:00:00 GMT-0400 (EST) alert (d);
Array methods

Join: This is the opposite of split, which will combine all the elements in the array to form a string

Alert (["Cats", "dogs", "hamsters", "Fish"].join (")"); // "Cats Dogs Hamsters Fish"alert ("This should is not having spaces". Split (""). Join ("_")); // "This_should_not_have_spaces"

Pop/shift:

var arr = ["Cats", "dogs", "hamsters", "fish"//  "fish"//  "Cats"  //  ["Dogs", "hamsters"]

Push/unshift:push will add a item,unshift at the end of the array to add an item at the beginning of the array

var arr = ["beta", "gamma"];arr.push ("Delta"//  ["Beta", "Gamma", "Delta"]; Arr.unshift ("Alpha"//  ["Alpha", "Beta", "Gamma", "Delta")

Reverse

Alert (["Crockford", "Resig", "Zakas"].reverse ());? // "Zakas, Resig, Crockford"

Slice: Sometimes you want to slice your array into multiple parts, and this slice provides this functionality. Contains two parameters: index of the starting element and index of the element after the last one want to slice.

Alert (["A", "B", "C", "D", "E"].slice (2, 4));? // ["C", "D"]alert (["F", "G", "H", "I", "J"].slice (1));? // ["G", "H", "I", "J"]

Sort: Sorted alphabetically by:

// ["A", "B", "C", "D",?" E "[0, 5, ten, +, 25].sort (); // [0, ten, 5].

The order of the numbers above may not be the effect you want, and one possible option is to have the sort function pass in a function:

var arr = [5, 2, 3, 4, 1,10,20];arr.sort (function  (A, b) {return A-  // [1, 2, 3, 4, 5, ten,];
Math functions

JavaScript also provides a math object, although you can't create objects two times as a Date object, but you can call the Math object's method directly

Min,max,random,round,ceil,floor,pow,

Alert (Math.min (9, 1, 4, 2));//1Alert (Math.random ());//0.5938208589795977 (you ll? )Probably get somethingElse) alert (Math.random ()* 10);//6.4271276677027345 (again,?your mileage may vary) alert (Math.Round (10.4));//TenAlert (Math.Round (10.5));// OneAlert (Math.ceil (10.4));// OneAlert (Math.floor (10.5));//Tenfunctiongetrandomnumberinrange (min, max) {returnMath.floor (Math.random () * (Max-min + 1) +? min);} Alert (Getrandomnumberinrange (0, 100));//You'll ?Probably get something different.
This

This is a keyword reserved by javascript and you can think of this as a dynamic variable that you cannot control. The value of this variable changes its value as you place it in the code:

By default, this will point to the Global object of window. This does not have a proper name, but he has a property pointing to itself: window. If you look at the little code below, you'll feel something:

var my_variable = "value"; function return "Another_value" this// "value"this/ / "Another_value"  var global = {Window:global};  this = global;

This means that you can access your global variables or functions as properties of the window, which is more common than accessing these global variable functions with this. This is still a bit of a mess, because you can access the Window object to use a function or property on the global object, even if this can point to other objects. You don't even have to call it by using window.xx, unless you have a local variable or function that overrides the global function or variable!

New keyword

The first way to change this pointer is to use the New keyword:

You probably know what JavaScript objects are (attributes and functions are encapsulated). Encapsulating the relevant functionality into a suitable object and accessing it through the appropriate interface is a very, very basic OOP programming pattern. Classes is like a blueprint: they are not actual objects, but they describe the functions and variables that the object should have once it creates an object from the class. JavaScript is object-oriented, but it does not use the concept of class. idea that it uses the concept of prototypes. Prototypes are some of the actual object objects that we can use to objects as a living Blueprint "object" for creating other objects.

In other languages, such as C + +, a constructor is used to create a new object. In JavaScript, the constructor is a normal function, and if you add a new keyword before it, you can create the object.

For example, we want to create a truck object,

function Truck (model) {this. num_of_tires = 4; this. kilometers = 0; this. Model = model;} var New Truck ("Hercules"); Console.log (My_truck);

The above code notes two points: first, we define all the variables as properties of this object; second, we do not return anything from this function. These two points are because we plan to use the New keyword to invoke this function to create an object. Notice how we use the New keyword. It does two things: first, it changes the this pointer to point to a new clean object. Obviously, we can then add our custom properties in this function. The second thing new is doing is: it returns this. Now the My_truck variable will point to the new object, and the My_truck is just like the result of our code:

var my_truck =40"Hercules"};console.log (My_truck);

This is the idea of using new: We get a super-simple way to create new objects. Obviously, you don't need to do this if you just need one or two simple objects. Usually you need this new mode when you need a lot of functionality and want to package it into an object, or you can use the new method to create an object when you want to create a series of similar objects.

Call and apply

The second way to change this pointer is call or apply. Everything in JavaScript is an object---even if function is an object. Since function is an object, they can also have properties and methods (Property,method). Call and apply are the two default methods for each function object.

The value of the existence of these two methods is to modify the this pointer in the function:

 function   Truck (model, num_of_tires) {   Num_of_tires;  this . kilometers = 0;  this . Model = model;}  var  basic_vehicle = {Year:2011 "Speedio", 4 

Tip: Primitive vs Reference values: You might think that while we're changing a known object, we'll lose those changes unless we assign them to a new variable. If the variable is a primitive value, then this will be true. However, objects (arrays) is Referrnce values:values passed by referrnce. A primitive value (such as a string or number) is stored in the computer's memory, And we use a variable to access it. When we pass this variable to a function, we copy that value to a new memory and point the function argument to the new copy memory, and the copy operation in the function, so the original primitive value is not changed. (because memory is different), but when we use reference value it is different: when we pass an object or an array to a function, the formal parameter points to the same memory as the original Object/array. This means that the this in Truck.call (basic_vehicle) and the basic_object in the outside of the function are completely a basic_object. So there's no need to do any assign action because Basic_ Vehicle now has all the properties assigned by truck. If we pay a variable for the return value of Truck.call (basic_vehicle), what will happen, it will be undefined, because truck without new will not return anything!

Here, we call the truck function by calling method of the truck function. The first argument to call is the object that we want to point to in the function. Since we are not using new to invoke truck, it will not create any new objects or return this. That's what we want, because we're just modifying objects that already exist, not recreating one!

After you become the object parameter that this is pointing to (you can refer to the context of the function), we can pass in any required parameters. These are the functions that will be executed as parameters are passed in. In the example above, the second parameter "Speedio" is passed to the truck function as its first parameter. The third parameter, 6, becomes the second parameter of the truck.

and call correspondence, there is also a method called apply. The difference between the two is that apply accepts only two parameters. The first is the context object, and the second is an array of parameters that will be passed into the function. This method is useful if you have a parameter as an array. For example

function Truck (model, num_of_tires) {this. num_of_tires = num_of_tires; this. kilometers = 0; this. Model = model;} var basic_vehicle = {year:2011= "Speedio"; Truck.apply (Basic_vehicle, User_input.split ("")); Console.log (basic_vehicle);
Inside an Object

There is another way to change the value of this.

var waitress ="Ashley"function= Customer | | "There!" ; return "Hi" + customer + "My name is" + ? this. name + "; What can I get to you? " ;}}; Alert (Waitress.greet (//  Hi Joe My name is? ) Ashley; What can I get to you?

JavaScript fundamental Concept

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.