JavaScript BASICS (recommended) and javascript Basics

Source: Internet
Author: User

JavaScript BASICS (recommended) and javascript Basics

Variables defined outside the function must be global variables. variables defined in the function are local variables if var is declared. If var is not declared, this variable is a global variable.

1. Global variables and local variables
JavaScript
var global = "Global";test();function test(){  var local = "Local";  document.writeln(global);  document.writeln(local);}document.writeln(global);document.writeln(local); 

2. Two types of cookies

I) Persistent cookies are stored on the client's hard disk.

Ii) Session cookie: The session cookie will not be stored on the client's hard disk, but stored in the memory of the browser process. When the browser is closed, the session cookie will be destroyed.

3. In JavaScript, a function is an object.

4. In JavaScript, there is no concept of method (function) overloading.

5. Function object

There is a Function object in JavaScript. All user-defined functions are Function object types. All parameters accepted by the Function object are of the string type. The last parameter is the Function body to be executed, and the previous parameter is the parameter that the Function really needs to accept.

6. Implicit object arguments

In JavaScript, each function has an implicit object arguments, indicating the parameters actually passed to the function. Arguments. length indicates the number of actually passed parameters.

7. function name. length

Each function object has a length attribute, indicating the number of parameters that the function expects to accept. It is different from the arguments of the function. Arguments. length indicates the number of parameters actually accepted by the function.

8. There are five primitive data types in JavaScript

Undefined, Null, Boolean, Number, and String. (Note: In JavaScript, there is no char data type)

The Undefined data type has only one value: undefined;

The Null data type has only one value: null;

Values of the Boolean data type include true and false;

9. typeof Operator

Typeof is a unary operator followed by the variable name. It is used to obtain the data type of a variable. Its return values include undefined, boolean, number, string, and object.

10. In JavaScript, if the function does not declare the return value, the relationship between undefined11, null, and undefined will be returned.

Undefined is actually derived from null. For example:

Relationship between null and undefined

JavaScript

Alert (undefined = null); // the browser returns true.

11. Forced type conversion

There are three forced conversions in JavaScript: Boolean (value), Number (value), String (value ).

12. Object

In JavaScript, all objects are inherited from Object objects.

Object

JavaScript

var object = new Object();for(var v in object){  alert(v);} 

In the above Code, the browser does not print anything and does not indicate that the Object does not have any attributes. The following code tests whether the attributes of an Object can be enumerated. If false is returned, the attributes of an Object cannot be enumerated.

Properties in an Object cannot be enumerated.

JavaScript

alert(object.propertyIsEnumerable("prototype")); 

If the "false" dialog box is displayed in the browser, the properties of the Object cannot be enumerated.

Next, let's see if the properties in the window object can be enumerated.

The properties in the window object can be enumerated.

JavaScript

for (var v in window) {  console.log(v);} 

In Chrome, we can see that a lot of properties are printed in the browser debugging console, which indicates that the properties in the window object can be enumerated.

13. In JavaScript, You can dynamically add or delete object attributes.

Dynamically Add/delete Object Attributes

JavaScript

Var object = new Object (); alert (object. username); // undefined object. username = "zhangsan"; alert (object. username); // zhangsan object ["password"] = "123"; alert (object. password); // 123 delete object. username; // at this time, the username attribute has been deleted by alert (object. username );

14. The most common way to define objects in JavaScript

The most common way to define objects

JavaScript

 var object = {  username:"zhangsan",  password:12345};alert(object.username);alert(object.password);

15. Array

Array Definition

JavaScript

// Method 1 var array = new Array (); array. push (1); array. push (2); array. push (3); alert (array. length); // method 2 (recommended) var array = [, 4]; array. sort (); alert (array );

The sort () method of the array is called, and the browser prints and 4, which is not the expected result.

For the sort method of JavaScript array, it first converts the content to be sorted into a string (call the toString () method) and sorts the content in the order of the string.

The following method is used to obtain the expected results (sorted by array size ):

Array sorting

JavaScript

function compare(num1,num2) {  var temp1 = parseInt(num1);  var temp2 = parseInt(num2);  if (temp1 < temp2) {    return -1;  } else if (temp1 == temp2) {    return 0;  } else {    return 1;  }} var array = [1,25,3];array.sort(compare);alert(array); 

We can use anonymous functions to achieve this:

Anonymous function sorting

JavaScript

var array = [1,25,3]; array.sort(function(num1,num2){  var temp1 = parseInt(num1);  var temp2 = parseInt(num2);  if (temp1 < temp2) {    return -1;  } else if(temp1 == temp2) {    return 0;  } else {    return 1;  }}); alert(array); 

16. Five methods for defining objects in JavaScript (no class concept in JavaScript, only objects) I) extend its attributes and methods based on existing objects

Extended attributes and methods based on existing objects

JavaScript

Var object = new Object (); // Add the name attribute object. name = "zhangsan"; // Add the sayName method object. sayName = function (name) {this. name = name; alert (this. name) ;}; object. sayName ("kyle"); // call the sayName method. The name attribute is changed to kyle and the browser prints kyle.

The simplest method is not convenient to use. It is suitable for temporarily requiring an object.

Ii) create objects in factory Mode

Factory method without parameters:

JavaScript

// Factory method function createObject () {var object = new Object (); // create an object. name = "zhangsan"; // Add a name attribute object for this object. password = "123"; // Add a password attribute object for this object. get = function () {// Add a get method alert (this. name + "," + this. password) ;}; return object; // return this object} var object1 = createObject (); // call the createObject factory method to create the object object1var object2 = createObject (); // call the createObject factory method to create the object object2object1. get (); // call the object get method object2.get (); // call the object get Method

Factory method with parameters:

JavaScript

function createObject(name,password) {  var object = new Object();  object.name = name;  object.password = password;  object.get = function() {    alert(this.name+","+this.password);  };  return object;} var object1 = createObject("zhangsan","123");var object2 = createObject("lisi","456");object1.get();object2.get(); 

Disadvantages of the above two factory methods without parameters and with parameters:

Each time an object is created, a get method is created in the memory, which is a waste of memory and affects performance. Our expectation is that the attributes of two different objects are different, but the methods are shared. Therefore, we need to improve the createObject factory method.

Improved factory methods:

JavaScript

function get(){  alert(this.name+","+this.password);} function createObject(name,password) {  var object = new Object();  object.name = name;  object.password = password;  object.get = get;  return object;} var object1 = createObject("zhangsan","123");var object2 = createObject("lisi","456");object1.get();object2.get(); 

Define the get method outside the createObject function, so that the get method is shared for every object created. Share a function object with multiple objects, rather than having one function object for each object.

Iii) create an object using Constructors

Constructors without parameters:

JavaScript

 

Function Person () {// before executing the first line of code, the js engine will generate an object for us this. name = "zhangsan"; this. password = "123"; this. getInfo = function () {alert (this. name + "," + this. password) ;}; // here is an implicit return statement used to return the previously generated object (which is also different from the factory method)} var p1 = new Person (); p1.getInfo ();

Constructors with Parameters

JavaScript

function Person(name,password) {  this.name = name;  this.password = password;  this.getInfo = function() {    alert(this.name+","+this.password);  };} var p1 = new Person("zhangsan","123");var p2 = new Person("lisi","456");p1.getInfo();p2.getInfo(); 

Iv) Create an object in prototype mode

Prototype is an attribute of an Object.

Prototype

JavaScript

Function Person () {} Person. prototype. name = "zhangsan"; Person. prototype. password = "123"; Person. prototype. getInfo = function () {alert (this. name + "," + this. password) ;}; var p1 = new Person (); var p2 = new Person (); p1.name = "kyle"; // change the property p1.getInfo () after the object is generated (); p2.getInfo ();

There are two problems with the prototype method: First, you cannot assign an initial value to the attribute in the constructor. You can only change the attribute value after the object is generated.

Prototype

JavaScript

function Person(){ }Person.prototype.name = new Array();Person.prototype.password = "123";Person.prototype.getInfo = function() {  alert(this.name+","+this.password);}; var p1 = new Person();var p2 = new Person();p1.name.push("zhangsan");p1.name.push("lisi");p1.password = "456";p1.getInfo();p2.getInfo() 

The browser will print: zhangsan, lisi, 456, zhangsan, lisi, 123.

If an object is created using a prototype, all the generated objects share the attributes in the prototype, so that an object changes this attribute and is also reflected in other objects. Therefore, it is impossible to simply use the prototype, but you also need to use other methods. Next we will continue to introduce it.

Define objects using prototype + Constructor

JavaScript

function Person() {  this.name = new Array();  this.password = "123";}Person.prototype.getInfo = function() {  alert(this.name+","+this.password);}; var p1 = new Person();var p2 = new Person();p1.name.push("zhangsan");p2.name.push("lisi");p1.getInfo();p2.getInfo(); 

The prototype + constructor is used to define objects. Attributes of objects do not interfere with each other. Each object shares the same method. This is a good method.

V) Dynamic Prototype

JavaScript

function Person(){  this.name = "zhangsan";  this.password = "123";  if(typeof Person.flag == "undefined"){    alert("invoked");    Person.prototype.getInfo = function(){      alert(this.name + "," + this.password);    }    Person.flag = true;  }    } var p1 = new Person();var p2 = new Person();p1.getInfo();p2.getInfo(); 

In the dynamic prototype mode, all objects share a method by using the flag in the constructor, and each object has its own attributes. When the code above creates an object for the first time, it first uses a judgment statement to check whether the flag attribute has been defined. If not, add the getInfo method in prototype mode and set the flag to true, when the object is created for the second time, the if statement is false and the execution is skipped. As a result, the created object attributes do not interfere with each other, and the object methods are shared.

 17. Inheritance of objects in JavaScript (5 methods)

Method 1: Object impersonate

Impersonate Object Inheritance

JavaScript

// Function Parent (username) {this. username = username; this. sayHello = function () {alert (this. username) ;}}// sub-class function Child (username, password) {// The following three lines of code are the most critical of this. method = Parent; this. method (username); delete this. method; this. password = password; this. sayWorld = function () {alert (this. password) ;};} var p = new Parent ("zhangsan"); var c = new Child ("lisi", "123"); p. sayHello (); c. sayHello (); c. sayWorld ()

Method 2: call ()

The second method of inheritance is the call method. The call method is the method defined in the Function object. Therefore, every Function we define has this method. The first parameter of the call method is passed to this in the function, and is assigned to the parameters in the function one by one starting with 2nd parameters.

Call inherits the parent class

JavaScript

Function test (str) {alert (this. name + "," + str);} var object = new Object (); object. name = "zhangsan"; // test. call is equivalent to calling the test function. call (object, "html5war"); // assigns the object to this

Next, we use the call method to implement Object Inheritance.

JavaScript

// Function Parent (username) {this. username = username; this. sayHello = function () {alert (this. username) ;};}// subclass function Child (username, password) {Parent. call (this, username); this. password = password; this. sayWorld = function () {alert (this. password) ;};} var p = new Parent ("zhangsan"); var c = new Child ("lisi", "123"); p. sayHello (); c. sayHello (); c. sayWorld ();

Method 3: apply ()

Apply inherits the parent class

JavaScript

// Function Parent (username) {this. username = username; this. sayHello = function () {alert (this. username) ;};}// subclass function Child (username, password) {Parent. apply (this, new Array (username); this. password = password; this. sayWorld = function () {alert (this. password) ;};} var p = new Parent ("zhangsan"); var c = new Child ("lisi", "123"); p. sayHello (); c. sayHello (); c. sayWorld ();

The apply method is similar to the call method. The apply method is also defined in the Function object. Therefore, every Function we define has this method.

The apply method differs from the call method: Parent. apply (this, new Array (username); the second parameter passed is an Array, while the call method transmits discrete data parameters. These two methods do not mean who is good or bad. They need to be used in specific scenarios.

Method 4: prototype chain (parameters cannot be passed to the constructor)

Prototype chain inheritance

JavaScript

function Parent() { }Parent.prototype.hello = "hello";Parent.prototype.sayHello = function() {  alert(this.hello);}; function Child() { }Child.prototype = new Parent(); Child.prototype.world = "world";Child.prototype.sayWorld = function() {  alert(this.world);}; var c = new Child(); c.sayHello();c.sayWorld(); 

Disadvantages of using the prototype chain: there is no way to pass parameters. You can modify the parameters only after the object is created. Next we will solve this problem with other methods.

Method 5: Hybrid (recommended)

Implement Object Inheritance in hybrid mode

JavaScript

function Parent(hello) {  this.hello = hello;}Parent.prototype.sayHello = function() {  alert(this.hello);} function Child(hello,world) {  Parent.call(this,hello);  this.world = world;}Child.prototype = new Parent();Child.prototype.sayWorld = function() {  alert(this.world);} var c = new Child("hello","world");c.sayHello();c.sayWorld(); 

The summary (recommended) of the above basic JavaScript knowledge points is all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support for the help house.

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.