JS in call/apply, arguments, Undefined/null method of detailed _javascript skills

Source: Internet
Author: User
Tags javascript array

A.call and apply method detailed
--------------------------------------------------------------------------------

Call 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 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 supplied, the Global object is used as a thisobj.

Apply method:

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

Definition: Applies one method of an object and replaces the current object with another object.

Note: If Argarray is not a valid array or is not a arguments object, it will result in a typeerror. If you do not supply any of the Argarray and thisobj parameters, the Global object will be used as a thisobj and cannot be passed any parameters.

Example Learning:

function Add (a,b) {alert (a+b);}
function sub (a,b) {alert (a-b);}

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

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, ",");//output result is "cat"

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

Implementing 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"); 

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

Extension: Multiple 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: JS inheritance There are other methods, such as the use of prototype chain, this is not part of the scope of this article, but here to explain the use of call. Said call, and of course, apply, these two methods are basically a meaning, the difference is that the second argument of call can be any type, and the second parameter of apply must be an array or arguments.

B.arguments use

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

What is arguments

Arguments is a built-in object in JavaScript, it's quirky and often overlooked, but it's really important. All the major JS libraries use the arguments object. So agruments objects must be familiar to JavaScript programmers.

All functions have a arguments object of their own, which includes the parameters to be invoked by the function. He is not an array, and if you use typeof arguments, it returns ' object '. Although we can call the arguments using the method that invokes 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 in use, but it's actually a very useful object. You can use the argument object to enable the function to invoke an indefinite number of arguments. There's a format function in Dean Edwards's Base2 library that shows 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 ', ' papers ', ' shirt ', ' wear '); result "and" papers want to know whose You wear "; Console print as

%1&1&8&and the%1 want to know whose%2/%3
%2&2&30&and the%1 want to know whose%2/%3
%3&3&37&and the%1 want to know whose%2/%3

Converts the arguments object into a true array

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

 
 

So now the variable args contains a standard JavaScript array object that contains all the parameters of the function.

Expanding: Using the Format function in the previous section to create a function from 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))); 
 

The method takes the first parameter out and returns a curry function whose arguments (the second arguments) synthesize the new array with the MAKEFUNC parameter group starting with the second argument. and returns the Apply call to the first argument of Makefunc

Perform

var majortom = makefunc (format, "This are Major Tom to ground control.") I ' m%1. ');

The results are: "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

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

The Callee property is a member of a 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 of the following example. This property is available only if the related function is executing. It is also necessary to note that callee has the length attribute, which is sometimes used for validation or better. The arguments.length is the length of the argument, and the arguments.callee.length is the length of the parameter (the parameters required in the definition), thus determining whether the parameter length is consistent with the actual parameter length.

Used to validate
the parameter function Calleelengthdemo (arg1, arg2) {
if (arguments.length==arguments.callee.length) {
Window.alert ("Verify parameter and argument length is correct!") ");
return;
} else {
alert ("Argument length:" +arguments.length);
Alert ("Parameter length:" +arguments.callee.length);
}
}
Recursively computes
var sum = function (n) {
if (n <= 0) return 1;
else return n +arguments.callee (n-1)
}
//Comparison general recursive function:
var sum = function (n) {
if (1==n) back 1;
   
    else return n + sum (n-1);
}
   

When invoked: Alert (SUM (100)); Where the function contains a reference to sum itself, the function name is just a variable name, within the function call sum is equivalent to call a global variable, not very good to reflect the call itself, then use callee would be a better way.

Expand Functionname.caller

Description: Returns who called the functionname function. The FunctionName object is the name of the function being executed. For functions, the caller property is only defined when the function executes. If the function is called by the top level, then caller contains null. If you use the Caller property in the string context, the result is the same as functionname.tostring, that is, the inverse compiled 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 was a top function");
}
function Handlecaller () {
callerdemo ();
}

Execution results:

C.undefined and Null

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

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

of similarity

In JavaScript, assigning a variable to undefined or null is, to be honest, almost indistinguishable.

The code is as follows:

var a = undefined;

In the code above, the A variable is assigned to undefined and null, and the two are almost equal to each other.

Undefined and null are automatically converted to false in an if statement, and the equality operator even reports directly to the same.

if (!undefined) 
console.log (' undefined is false ');
Undefined is false
if (!null) 
console.log (' null is false ');
Null is false
undefined = null

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

typeof null;//"Object"

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

Historical reasons

Originally, this is related to the history of JavaScript. When JavaScript was born in 1995, it was originally like Java, setting only null as a value that represented "none."

According to the C language tradition, NULL is designed to be automatically converted to 0.

Number (NULL)//0
5 + NULL//5

But Brendan Eich, a JavaScript designer, feels it's not enough, for 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, the original type (primitive) and the composite type (complex), Brendan Eich feel that the value representing "None" is best not an object.

Second, the original version of JavaScript did not include the error handling mechanism, when the data type mismatch occurred, often the automatic conversion type or silently failed. Brendan eich that if NULL automatically to 0, it is not easy to find errors. Therefore, Brendan Eich also designed a undefined.

Originally designed

The original version of JavaScript is distinguished by this: null is an object that represents "none", and when converted to a value, 0;undefined is an original value representing "None", which is Nan when converted to a value.

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

The current usage

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

Null means "No object", where there should be no value. Typical uses are:

(1) as a parameter of the function, which indicates that 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," where there should be a value, but not yet defined. Typical uses are:

(1) When a variable is declared, it is equal to undefined when it is not assigned a value.

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

(3) The object has no assigned property, and the value of the property is undefined.

(4) When the function does not return a value, the default returns undefined.

var i;
I//undefined
function f (x) {Console.log (x)}
F ()//undefined
var o = new Object ();
O.P//undefined
var x = f ();

The above is a small set to introduce you to the JS call/apply, arguments, Undefined/null method, I hope to help.

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.