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);} }function Cat () {this.name = "cat" ; } var animal = new animal (); var cat = new Cat (); Animal.showName.call (Cat, ","); // output is "Cat" // 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;   function () {alert (thisfunction, Cat (name) {Animal.call (thisnew 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 () {function (b) {  alert (A-b);}} function Class11 () {function (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 is 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;  New RegExp ('% ([1-' + Arguments.length + ']) ', ' G '); function(match, Index,position,all) {console.log (match + ' & ' + index + ' & ' + position + ' & ' + al L); 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 =functionreturn 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 , and arguments.callee.length is the length of the formal parameter (therequired 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 parameters and argument lengths are correct!") ");Return; }Else{Alert (argument length: "+Arguments.length); Alert ("Parameter length:" +Arguments.callee.length); }}// recursive calculation var sum = function (n) {if (n <= 0) return 1;return n +arguments.callee (n-1// more general recursive functions: var sum =  (n) { return 1; else return n + 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=else {alert ("This I S 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 this?

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;  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 falseif (!  Null) Console.log (' null is false ');  NULL is falsenull// 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

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 (//// 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.

"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// undefinednew// undefinedvar x =//  Undefined          

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

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.