JS Basic article--call/apply, arguments, undefined/null

Source: Internet
Author: User
Tags javascript array

A.call and Apply Method Pager Method :

Syntax: Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])

Definition: Invokes one method of an object, replacing the current object with another object.

Description: The call method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Thisobj. If the Thisobj parameter is not provided, then the Global object is used as the thisobj.

Apply Method:

Syntax: Apply ([Thisobj[,argarray]])

Definition: A method of applying an object that replaces the current object with another object.

Description: If Argarray is not a valid array or is not a arguments object, it will result in a TypeError. If none of the Argarray and Thisobj parameters are provided, then the Global object is used as a thisobj and cannot be passed any parameters.

Example Learning:

function Add (b) {alert (A +b);} function Sub (b) {alert (A-b);} Add.call (Sub,3,1);

The print result is 4. The Add function is called, but the calling object (the context) is not an Add object, but a sub function object. Note: The function in JS is actually an object, and the function name is a reference to a function object.

functionAnimal () { This. Name = "Animal";  This. ShowName =function() {Alert ( This. name);} }functionCat () { This. Name = "Cat"; } varAnimal =NewAnimal ();varCat =NewCat (); Animal.showName.call (Cat,",");//the output is "Cat"animal.showName.apply (cat,[]);//the output is "Cat"

Call means to put the animal method on the cat, the context is cat, the original cat is no ShowName () method, now is to put the animal ShowName () method on the cat to perform, and Cat's this.name is cat. So this.name should be Cat

Implementing inheritance

function Animal (name) {   this. Name = name;      This function () {  alert (this. name);}   }    function Cat (name) {  Animal.call (this, name);}    var New Cat ("Black cat");  Cat.showname ();

Animal.call (this) means calling the Animal method, but using the this object instead of the Animal object, the context becomes this. The new Cat ("Black cat") uses Animal.call to set the property name and method ShowName for the current context environment.

Expand: Multiple Inheritance

function Class10 () {thisfunction(b) {  alert (A-b);}} function Class11 () {thisfunction(b) {   alert (A +B);    }} function Class2 () {    Class10.call (this);    Class11.call (this);}

Note: JS inheritance There are other methods, such as the use of prototype chain, this is not part of the scope of this article, just here to illustrate the use of call. Call, and of course, apply, these two methods are basically a meaning, the difference is that the second parameter of call can be any type, and the second argument of apply must be an array or arguments.

B.arguments use What is arguments

  arguments It's a built-in object in JavaScript, it's weird and often overlooked, but it's really important. All major JS libraries take advantage of the arguments object. So agruments objects are necessary for JavaScript programmers to be familiar with.

All functions have a arguments object of their own, which includes the parameters to be called by the letter. He is not an array, and if you use typeof arguments, the return is ' object '. Although we can call arguments with the method of invoking the data. such as length, and the index method. However, the push and pop objects of the array are not applicable.

Use arguments to create a flexible function

It looks like the argument object is very limited to use, but it's actually a very useful object. You can use the argument object to allow the function to invoke a variable number of arguments . There's a formatted function in Dean Edwards's Base2 library that shows this flexibility.

function Format (string) {var args = arguments; var New REGEXP ('% ([1-' + Arguments.length + ']) ', ' G '); return function (Match, Index,position,all) {          + ' & ' + index + ' & ' + position + ' & ' + all ); return Args[index];   };

Dropped with format (' and the%1 want to know whose%2 ', ' papers ', ' shirt ', ' wear '); The result is "and the papers want to know whose shirt You wear "; the console is printed as

%1&1&8&and the%1 want to know whose%2 you%3

%2&2&30&and the%1 want to know whose%2 you%3

%3&3&37&and the%1 want to know whose%2 you%3

Convert the arguments object to a real array

Although the arguments object is not a true JavaScript array, we can easily convert it to standard data and then manipulate the array.

var args = Array.prototype.slice.call (arguments);

Now this variable, args, contains a standard JavaScript array object with all the parameters of the function.

Expand: Use the Format function of the previous section to create a function from a preset arguments object

function Makefunc () {   var args = Array.prototype.slice.call (arguments);    var func = args.shift ();    return function () {   return func.apply (null, Args.concat (Array.prototype.slice.call ( arguments)));       }    ;}

The method takes the first parameter out and then returns a curry function, which curry the parameter (the second arguments) to the new array that makefunc the parameter group starting with the second argument. and returns the apply call of the first parameter of Makefunc

Perform

var majortom = makefunc (format, "This was Major Tom to ground control. I ' m%1. " ); MajorTom ("stepping through the door");

The result: "This is Major Tom to ground control." I ' m stepping through the door. "

Console printing:%1&1&41&this is Major Tom to ground control. I ' m%1.

[function.] Arguments.callee

Description: The Arguments.callee method returns the function itself that is being executed.

The Callee property is a member of the arguments object that represents a reference to the function object itself, which facilitates the recursion of anonymous functions or guarantees the encapsulation of functions, such as the sum of the natural numbers of 1 to n for the recursive calculation of the example below. This property is available only if the related function is executing. It is also important to note that callee has the length property , which is sometimes used for validation or better. Arguments.length is the length of the argument, andarguments.callee.length is the length of the formal parameter (the required parameter as defined), thus determining whether the parameter length in the call is consistent with the length of the argument.

//used to validate parametersfunctionCalleelengthdemo (arg1, arg2) {if(arguments.length==arguments.callee.length) {Window.alert ("Verify that the formal parameters and argument lengths are correct!" ");return; } Else{alert ("Argument length:" +arguments.length); Alert ("Parameter length:" +arguments.callee.length); }}//Recursive calculationvarsum =function(n) {if(n <= 0)return1;Else returnN +arguments.callee (n-1)}//comparison of general recursive functions:varsum =function(n) {if(1==n)return1;Else returnn + sum (n-1);}

Call: Alert (SUM (100)), where the function contains a reference to the sum itself, the function name is just a variable name, call sum within the function is equivalent to calling a global variable, does not well reflect the call itself, when using callee will be a better method.

Expand Functionname.caller

Description: Returns who called the functionname function. The FunctionName object is the name of the function being executed. For a function, the caller property is defined only when the function executes. If the function is called by the top level, then caller contains null. If you use the Caller property in a string context, the result is the same as functionname.tostring, that is, the deserialized text of the function is displayed. The following example illustrates the use of the caller property:

// Caller Demo {function  Callerdemo () {if  (callerdemo.caller) {var a= callerDemo.caller.toString ();    alert (a);   Else {    alert ("This is a top function");}  } function Handlecaller () {  callerdemo ();} Handlecaller ();

Execution Result:

  

  

C.undefined and Null

Most computer languages have and have only one value that represents "none", for example, the Null,java language of the C language, the Null,python language of the None,ruby language of nil. Oddly enough, the JavaScript language actually has two values that represent "none": Undefined and null. Why is that?

Similarity of
In JavaScript, a variable is assigned a value of undefined or null, to be honest, almost indistinguishable.

The code is as follows:

var a = undefined; var null;

In the above code, the A variable is assigned a value of undefined and null, which is almost equal to each other.

Undefined and null are automatically converted to false in the IF statement, and the equality operator even reports that they are equal.

if (! undefined)     Console.log (' undefined is false '); // undefined is false if (! NULL )     console.log (' null is False '); // Null is False  null//  true

The code above shows how similar the two behaviors are! But we're going to look at the individual types of undefined and null but find that the types are different. No null type in JS base type

typeof null; // "Object" typeof undefined; // "undefined"

  Since the meaning of undefined and null is similar to that of usage, why should you set two such values at the same time, which is not an unwarranted increase in the complexity of JavaScript, so that beginners are troubled? The dart language, an alternative to the JavaScript language developed by Google, explicitly stipulates that only null, no undefined!

Historical reasons

Originally, this is related to the history of JavaScript. When JavaScript was born in 1995, initially, like Java, only null was set as the value representing "none".

According to the traditional C language, NULL is designed to automatically convert to 0.

Number (null//  0null//  5

However, JavaScript designers Brendan Eich that this is not enough, there are two reasons.

First, NULL is treated as an object, as in Java.

typeof NULL // "Object"

However, the data type of JavaScript is divided into two categories: primitive type (primitive) and composition type (complex), Brendan Eich think that the value of "none" is best not an object.

Second, the initial version of JavaScript does not include the error handling mechanism, when data type mismatch occurs, is often the type of automatic conversion or silently fail. Brendan Eich feels that if NULL is automatically converted to 0, it is not easy to find an error. Therefore, Brendan Eich also designed a undefined.

Original design

The original version of JavaScript is distinguished by the following:null is an object that represents "none", and a value of 0;undefined is a primitive value that represents "none" and Nan when converted to a numeric value.

Number (undefined)  //  nan5 + undefined  //  nan

The current usage

However, the above distinction, in practice, is quickly proved to be not OK. At present, null and undefined are basically synonymous, with only a few subtle differences.

  null means "No object", that is, there should be no value at all. Typical uses are:

(1) As a function parameter, the parameter of the function is not an object.

(2) As the end point of the object prototype chain.

Object.getprototypeof (object.prototype)  //  null

  undefined means "missing value", that is, there should be a value here, but there is no definition . Typical uses are:

(1) The variable is declared, but when it is not assigned, it is equal to undefined.

(2) when calling a function, the argument that should be supplied is not provided, which equals undefined.

(3) The object does not have an assigned property, and the value of this property is undefined.

(4) When the function does not return a value, undefined is returned by default.

var//  undefinedfunction//  undefinedvar   new//  undefinedvar x =// undefined

The above article is part of the article from the online record of the ancient notes, the record when no indication of the source is now also not good to find, if a Daniel past found that contains your blog post, please indicate the source in the comments, I fill in, thank you.

  

  If you feel this article is good, please click on the bottom right "recommended"!

JS Basic article--call/apply, arguments, undefined/null

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.