Home > Article > Web Front-end > Detailed explanation of call/apply, arguments, and undefined/null methods in JS
a.Detailed explanation of call and apply methods
---------------------------------------- -----------------------------------------------
call Method:
Syntax: call([thisObj[,arg1[, arg2[, [,.argN]]]]])
Definition: Call an object A method that replaces the current object with another object.
Description: The call method can be used to call a method instead of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj. If no thisObj parameter is provided, the Global object is used as thisObj.
apply method:
Syntax: apply([thisObj[,argArray]])
Definition: Apply an object of a certain object Method that replaces the current object with another object.
Description: If argArray is not a valid array or is not an arguments object, a TypeError will be caused. If neither argArray nor thisObj are provided, the Global object will be used as thisObj and no parameters can be passed.
Example study:
function add(a,b){ alert(a+b);} function sub(a,b){ alert(a-b);} add.call(sub,3,1);
The printed result is 4. The add function is called, but the calling object (context) is not the add object, but the sub function object. Note: Functions in js are actually objects, and the function name is a reference to the 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,",");//输出结果为"Cat" animal.showName.apply(cat,[]);//输出结果为"Cat"
call means to put the animal method on cat for execution. The context is cat. Originally, cat did not have a showName() method. Now it is The showName() method of animal is placed on cat for execution, and the this.name of cat 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 using this object instead of Animal object, the context becomes this. Animal.call is used in new Cat("Black Cat") to set the attribute name and method showName for the current context.
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: There are other ways to inherit js, such as using the prototype chain, this does not belong The scope of this article is just to explain the usage of call. Speaking of call, and of course apply, these two methods basically mean the same thing. The difference is that the second parameter of call can be of any type, while the second parameter of apply must be an array or arguments.
b.arguments use
--------------------------- -------------------------------------------------- --
What are arguments
Arguments is a built-in object in JavaScript. It is weird and often overlooked, but it is actually very important. All major JavaScript libraries utilize the arguments object. Therefore, the agruments object must be familiar to JavaScript programmers.
All functions have their own arguments object, which contains the parameters to be called by the function. It is not an array. If typeof arguments are used, 'object' is returned. Although we can call arguments using the method of calling data. For example, length and index methods. But array push and pop objects are not applicable.
Use arguments to create a flexible function
It may seem that the argument object is very limited in use, but in fact it is a very useful object. You can enable a function to be called with a variable number of arguments by using the argument object. There is a formatting function in Dean Edwards' base2 library that demonstrates 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]; }); };
Instead of using 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"; the console print is
%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 into a real array
Although the arguments object is not a real JavaScript array, we can still easily convert it into standard data and then perform array operations.
var args = Array.prototype.slice.call(arguments);
Now the variable args contains a standard javascript array object containing all the parameters of the function.
Extension: 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 will The first parameter is taken out, and then a curry function is returned. The parameters of the curry function (the second arguments) will be combined with the parameters starting from the second parameter of makeFunc into a new array. And return the apply call of the first parameter of makeFunc
Execution
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
说明:arguments.callee方法返回的是正在执行的函数本身。
callee 属性是 arguments 对象的一个成员,它表示对函数对象本身的引用,这有利于匿名函数的递归或者保证函数的封装性,例如下边示例的递归计算1到n的自然数之和。而该属性仅当相关函数正在执行时才可用。还有需要注意的是callee拥有length属性,这个属性有时候用于验证还是比较好的。arguments.length是实参长度,arguments.callee.length是形参(定义时规定的需要的参数)长度,由此可以判断调用时形参长度是否和实参长度一致。
//用于验证参数 function calleeLengthDemo(arg1, arg2) { if (arguments.length==arguments.callee.length) { window.alert("验证形参和实参长度正确!"); return; } else { alert("实参长度:" +arguments.length); alert("形参长度: " +arguments.callee.length); } } //递归计算 var sum = function(n){ if (n <= 0) return 1; else return n +arguments.callee(n - 1) } //比较一般的递归函数: var sum = function(n){ if (1==n) return 1; else return n + sum (n-1); }
调用时:alert(sum(100));其中函数内部包含了对sum自身的引用,函数名仅仅是一个变量名,在函数内部调用sum即相当于调用一个全局变量,不能很好的体现出是调用自身,这时使用callee会是一个比较好的方法。
拓展 functionName.caller
说明: 返回是谁调用了functionName 函数。functionName 对象是所执行函数的名称。对于函数来说,caller 属性只有在函数执行时才有定义。如果函数是由顶层调用的,那么 caller 包含的就是 null 。如果在字符串上下文中使用 caller 属性,那么结果和 functionName.toString 一样,也就是说,显示的是函数的反编译文本。 下面的例子说明了 caller 属性的用法:
// 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();
执行结果:
c.undefined和null
--------------------------------------------------------------------------------
大多数计算机语言,有且仅有一个表示"无"的值,比如,C语言的NULL,Java语言的null,Python语言的none,Ruby语言的nil。有点奇怪的是,JavaScript语言居然有两个表示"无"的值:undefined和null。这是为什么?
相似性
在JavaScript中,将一个变量赋值为undefined或null,老实说,几乎没区别。
代码如下:
var a = undefined; var a = null;
上面代码中,a变量分别被赋值为undefined和null,这两种写法几乎等价。
undefined和null在if语句中,都会被自动转为false,相等运算符甚至直接报告两者相等。
if (!undefined) console.log('undefined is false'); // undefined is false if (!null) console.log('null is false'); // null is false undefined == null // true
上面代码说明,两者的行为是何等相似!但是我们去查看undefined和null的各自的类型却发现类型是不同的。js基础类型中没有null类型
typeof null;//"object" typeof undefined;//"undefined"
既然undefined和null的含义与用法都差不多,为什么要同时设置两个这样的值,这不是无端增加JavaScript的复杂度,令初学者困扰吗?Google公司开发的JavaScript语言的替代品Dart语言,就明确规定只有null,没有undefined!
历史原因
原来,这与JavaScript的历史有关。1995年JavaScript诞生时,最初像Java一样,只设置了null作为表示"无"的值。
根据C语言的传统,null被设计成可以自动转为0。
Number(null) // 0
5 + null // 5
但是,JavaScript的设计者Brendan Eich,觉得这样做还不够,有两个原因。
首先,null像在Java里一样,被当成一个对象。
typeof null // "object"
但是,JavaScript的数据类型分成原始类型(primitive)和合成类型(complex)两大类,Brendan Eich觉得表示"无"的值最好不是对象。
其次,JavaScript的最初版本没有包括错误处理机制,发生数据类型不匹配时,往往是自动转换类型或者默默地失败。Brendan Eich觉得,如果null自动转为0,很不容易发现错误。因此,Brendan Eich又设计了一个undefined。
最初设计
JavaScript的最初版本是这样区分的:null是一个表示"无"的对象,转为数值时为0;undefined是一个表示"无"的原始值,转为数值时为NaN。
Number(undefined) // NaN
5 + undefined // NaN
目前的用法
但是,上面这样的区分,在实践中很快就被证明不可行。目前,null和undefined基本是同义的,只有一些细微的差别。
null表示"没有对象",即该处不应该有值。典型用法是:
(1) 作为函数的参数,表示该函数的参数不是对象。
(2) 作为对象原型链的终点。
Object.getPrototypeOf(Object.prototype) // null
undefined表示"缺少值",就是此处应该有一个值,但是还没有定义。典型用法是:
(1)变量被声明了,但没有赋值时,就等于undefined。
(2) 调用函数时,应该提供的参数没有提供,该参数等于undefined。
(3)对象没有赋值的属性,该属性的值为undefined。
(4)函数没有返回值时,默认返回undefined。
var i; i // undefined function f(x){console.log(x)} f() // undefined var o = new Object(); o.p // undefined var x = f(); x // undefined
以上所述是小编给大家介绍的Detailed explanation of call/apply, arguments, and undefined/null methods in JS,希望对大家有所帮助。
更多Detailed explanation of call/apply, arguments, and undefined/null methods in JS相关文章请关注PHP中文网!