码迷,mamicode.com
首页 > 移动开发 > 详细

callee(),call(),apply()方法的使用

时间:2017-03-27 14:18:03      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:ati   语法   全局   定义   script   his   字符   nbsp   apply()   

argiments(类数组对象):实参对象的引用。

用法:当调用函数的时候传入的实参个数超过函数定义时的形参个数时,没有办法直接获得未命名值得引用时,就可以使用arguments,通过数字下标访问传入函数的实参值

arguments.callee:指代当前正在执行的函数。

用法:匿名函数中通过callee来递归调用自身

var c=function (x) {
if(x<=1){
return 1
}
return x*arguments.callee(x-1)
}

arguments.length:表示传入函数的实参的个数

arguments.callee.length:表示期望传入的实参个数,即形参个数

 

 

call()方法和apply()方法

call语法:

fun.call(thisArg[, arg1[, arg2[, ...]]])

参数

thisArg

在fun函数运行时指定的this值。需要注意的是,指定的this值并不一定是该函数执行时真正的this值,如果这个函数处于非严格模式下,则指定为null和undefined的this值会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象。

arg1, arg2, ...

指定的参数列表。

返回值

返回结果包括指定的this值和参数。

例子

1.使用call方法调用匿名函数

var animals = [
{species: ‘Lion‘, name: ‘King‘},
{species: ‘Whale‘, name: ‘Fail‘}
];

for (var i = 0; i < animals.length; i++) {
(function (i) {
this.print = function () {
console.log(‘#‘ + i + ‘ ‘ + this.species + ‘: ‘ + this.name);
}
this.print();
}).call(animals[i], i);
}

2.使用call方法调用父构造函数

function Product(name, price) {
this.name = name;
this.price = price;

if (price < 0) {
throw RangeError(‘Cannot create product ‘ +
this.name + ‘ with a negative price‘);
}
}

function Food(name, price) {
Product.call(this, name, price);
this.category = ‘food‘;
}


apply语法:

fun.apply(thisArg[, argsArray])

参数

thisArg

在 fun 函数运行时指定的 this 值。需要注意的是,指定的 this 值并不一定是该函数执行时真正的 this 值,如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的 this 会指向该原始值的自动包装对象。

argsArray

一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 fun 函数。如果该参数的值为null 或 undefined,则表示不需要传入任何参数。从ECMAScript 5 开始可以使用类数组对象。浏览器兼容性请参阅本文底部内容。

例子

使用Math.max/Math.min来找出一个数组中的最大/最小值。

var numbers = [5, 6, 2, 3, 7];

var max = Math.max.apply(null, numbers);
var min = Math.min.apply(null, numbers)

callee(),call(),apply()方法的使用

标签:ati   语法   全局   定义   script   his   字符   nbsp   apply()   

原文地址:http://www.cnblogs.com/gaaraxt/p/6626436.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!