Details about call/apply, arguments, and undefined/null methods in JS, argumentsundefined

Source: Internet
Author: User
Tags javascript array

Details about call/apply, arguments, and undefined/null methods in JS, argumentsundefined

A. Detailed description of call and apply methods
--------------------------------------------------------------------------------

Call method:

Syntax: call ([thisObj [, arg1 [, arg2 [, [,. argN])

Definition: call a method of an object to replace the current object with another object.

Note: The call method can be used to call a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by thisObj. If the thisObj parameter is not provided, the Global object is used as thisObj.

Apply method:

Syntax: apply ([thisObj [, argArray])

Definition: apply a method of an object and replace the current object with another object.

NOTE: If argArray is not a valid array or an arguments object, a TypeError occurs. If neither argArray nor thisObj is provided, the Global object will be used as thisObj and cannot be passed with any parameters.

Instance learning:

function add(a,b){ alert(a+b);}function sub(a,b){ alert(a-b);}add.call(sub,3,1); 

The print result is 4. The add function is called, but the calling object (Context Environment) is not the add object, but the sub function object. Note: Functions in js are actually objects, and Function names are references to Function objects.

Function Animal () {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, ","); // The output is "Cat" animal. showName. apply (cat, []); // The output result is "Cat"

Call means to put the animal Method on cat for execution, the context environment is cat, the original cat is not the showName () method, now is to put animal showName () the method is put on the cat and the cat's this. the name is Cat. So this. name should be Cat

Implement inheritance

function Animal(name){ this.name = name; this.showName = function(){ alert(this.name);} } function Cat(name){ Animal.call(this, name); } var cat = new Cat("Black Cat"); cat.showName(); 

Animal. call (this) means to call the Animal method, but use this object instead of the Animal object, and the context environment changes to this. In new Cat ("Black Cat"), Animal. call is used to set the attribute name and method showName for the current context.

Expansion: Multi-Inheritance

function Class10(){this.showSub = function(a,b){ alert(a-b); }}function Class11(){this.showAdd = function(a,b){ alert(a+b); }}function Class2(){Class10.call(this);Class11.call(this);}

Note: There are other methods for js inheritance. For example, using prototype chain does not fall into the scope of this article. It only describes the call usage here. When we talk about call and apply, the two methods basically mean one thing. The difference is that the second parameter of call can be of any type, the second parameter of apply must be an array or arguments.

B. Use arguments

--------------------------------------------------------------------------------

What is arguments?

Arguments is a built-in object in JavaScript. It is odd and often overlooked, but it is actually very important. All major js function libraries use the arguments object. Therefore, the agruments object must be familiar to javascript programmers.

All functions have their own arguments object, which includes the parameters to be called. It is not an array. If typeof arguments is used, 'object' is returned '. Although we can call arguments by calling the data method. For example, length and index methods. However, the push and pop objects in several groups are not applicable.

Use arguments to create a flexible function

It seems that the argument object is very limited to use, but it is actually a very useful object. You can use an argument object to allow the function to call a variable number of parameters. There is a Formatting Function in Dean Edwards's base2 library, demonstrating this flexibility.

function format(string) {var args = arguments;var pattern = new RegExp('%([1-' + arguments.length + '])', 'g');return String(string).replace(pattern, function(match, index,position,all) { console.log(match + '&' + index + '&' + position + '&' + all);return args[index]; }); }; 

Drop format ('And the % 1 want to know whose % 2 you % 3', 'papers', 'shirt', 'wear '); the result is "And the papers want to know whose shirt you wear ".

% 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

Converts an arguments object into a real array.

Although the arguments object is not a real javascript array, we can easily convert it into standard data and then perform Array Operations.

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

Now the args variable contains a standard javascript Array object containing all the parameters of the function.

Extended: use the format function in the previous section to create a function through the 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))); }; } 

This method retrieves the first parameter and returns a curry function. The parameter of this curry function (the second arguments) the parameters starting with the second parameter of makeFunc are combined into a new array. And returns the apply call of the first makeFunc parameter.

Run

var majorTom = makeFunc(format, "This is Major Tom to ground control. I'm %1.");majorTom("stepping through the door"); 

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

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

[Function.] arguments. callee

Note: The arguments. callee method returns the function itself being executed.

The callee attribute is a member of the arguments object. It indicates a reference to the function object itself. This facilitates recursion of anonymous functions or ensures function encapsulation, for example, the following example recursively calculates the sum of natural numbers from 1 to n. This attribute is only available when the related function is being executed. It should also be noted that callee has the length attribute, which is sometimes used for verification. Arguments. length is the length of the real parameter, and arguments. callee. length is the length of the form parameter (required parameter when defined). It can be used to determine whether the length of the form parameter is consistent with the actual length.

// Verify that the Parameter function calleeLengthDemo (arg1, arg2) {if (arguments. length = arguments. callee. length) {window. alert ("verify that the parameter length is correct! "); Return;} else {alert (" real parameter length: "+ arguments. length); alert ("parameter length:" + arguments. callee. length) ;}// recursively calculate var sum = function (n) {if (n <= 0) return 1; else return n + arguments. callee (n-1)} // a general recursive function: var sum = function (n) {if (1 = n) return 1; else return n + sum (n-1 );}

Call time: alert (sum (100). The function contains a reference to sum itself. The function name is just a variable name, calling sum in a function is equivalent to calling a global variable. It cannot reflect itself. Using callee is a better method.

Extended functionName. caller

Description: who calls the functionName function. The functionName object is the name of the executed function. For a function, the caller attribute is defined only when the function is executed. If the function is called by the top layer, caller contains null. If the caller attribute is used in the string context, the result is the same as functionName. toString, that is, the decompilation Text of the function is displayed. The following example illustrates the usage of caller attributes:

// 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 only one value indicating "none", such as NULL in C, null in Java, none in Python, and nil in Ruby. It is strange that the JavaScript language has two "NONE" values: undefined and null. Why?

Similarity

In JavaScript, assign a variable to undefined or null. To be honest, there is almost no difference.

The Code is as follows:

var a = undefined;var a = null; 

In the above Code, variables a are assigned undefined and null, which are almost equivalent.

Both undefined and null are automatically converted to false in the if statement. The Equal operator even directly reports that the two are equal.

if (!undefined) console.log('undefined is false');// undefined is falseif (!null) console.log('null is false');// null is falseundefined == null// true 

The code above shows how similar the two are! However, we can check the respective types of undefined and null but find that the types are different. The js basic type does not contain the null type.

typeof null;//"object"typeof undefined;//"undefined" 

Since the meanings and usage of undefined and null are similar, why do we need to set two such values at the same time? Doesn't it add JavaScript complexity without reason, and does it bother beginners? Dart, a replacement for JavaScript language developed by Google, makes it clear that there is only null, no undefined!

Historical Reasons

Originally, this was related to the history of JavaScript. When JavaScript was born in 1995, just like Java, only null was set as the value indicating "NONE.

According to the traditional C language, null is designed to be automatically converted to 0.

Number (null) // 0
5 + null // 5

But Brendan Eich, the JavaScript designer, thinks this is not enough for two reasons.

First, null is treated as an object like in Java.

Typeof null // "object"

However, JavaScript data types are divided into two categories: primitive and complex. Brendan Eich thinks that the value indicating "NONE" is better not an object.

Second, the original version of JavaScript does not include an error handling mechanism. When data types do not match, the type is automatically converted or fails silently. Brendan Eich thinks that if null is automatically converted to 0, it is not easy to find errors. Therefore, Brendan Eich designed an undefined.

Initial Design

The original version of JavaScript is distinguished as follows: null is an object indicating "NONE", and the value is 0 when it is converted to a value; undefined is an original value indicating "NONE" and NaN when it is converted to a value.

Number (undefined) // NaN
5 + undefined // NaN

Current usage

However, the above distinction will soon prove unfeasible in practice. Currently, null and undefined are basically synonymous, with only slight differences.

Null indicates "no object", that is, there should be no value. Typical usage:

(1) As a function parameter, it indicates that the function parameter is not an object.

(2) serves as the end point of the object prototype chain.

Object. getPrototypeOf (Object. prototype) // null

Undefined indicates "Missing Value", that is, there should be a value, but it is not defined yet. Typical usage:

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

(2) When calling a function, the required parameter is not provided. This parameter is equal to undefined.

(3) The object does not have an attribute assigned a value. The value of this attribute is undefined.

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

var i;i // undefinedfunction f(x){console.log(x)}f() // undefinedvar o = new Object();o.p // undefinedvar x = f();x // undefined 

The above is a detailed description of the call/apply, arguments, undefined/null methods in Javascript. I hope this will help you.

Articles you may be interested in:
  • Example and understanding of arguments, caller, callee, call, and apply in javascript
  • Summary of arguments, caller, callee, and apply in js

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.