Heim > Web-Frontend > js-Tutorial > Hauptteil

Javascript学习笔记之函数篇(四):arguments 对象_基础知识

WBOY
Freigeben: 2016-05-16 16:30:34
Original
1264 Leute haben es durchsucht

每一个 Javascript 函数都能在自己作用域内访问一个特殊的变量 - arguments。这个变量含有一个传递给函数的所有参数的列表。
arguments 对象不是一个数组。尽管在语法上它跟数组有相同的地方,例如它拥有 length 属性。但它并不是从 Array.prototype 继承而来,实际上,它就是一个对象。
因此,我们不能直接对 arguments 使用一些数组的方法,例如 push, pop 或 slice 等。 所以为了使用这些方法,我们就需要将其转换为一个真正的数组。

转化为数组

下面的代码将会返回一个包含 arguments 对象所有元素的数组。

Array.prototype.slice.call(arguments);
由于转化的速度很慢,所以在性能要求严格的程序中不建议这样做。

传递参数

下面是一种比较推荐的方法,将 arguments 对象从一个函数传递到另一个函数。

复制代码 代码如下:

function foo() {
    bar.apply(null, arguments);
}
function bar(a, b, c) {
    // do stuff here
}

另外还有一个比较巧妙的方法,就是同时使用 call 和 apply 快速创建一个解绑的外层方法。

复制代码 代码如下:

function Foo() {}
Foo.prototype.method = function(a, b, c) {
    console.log(this, a, b, c);
};
// Create an unbound version of "method"
// It takes the parameters: this, arg1, arg2...argN
Foo.method = function() {
    // Result: Foo.prototype.method.call(this, arg1, arg2... argN)
    Function.call.apply(Foo.prototype.method, arguments);
};

函数形参和 arguments 属性的关系

arguments 对象为它自身属性和函数的形参都创建了 getter 和 setter 方法。
因此,修改函数的形参会影响对应的 arguments 对象的属性值,反之亦然。

复制代码 代码如下:

function foo(a, b, c) {
    arguments[0] = 2;
    a; // 2
    b = 4;
    arguments[1]; // 4
    var d = c;
    d = 9;
    c; // 3
}
foo(1, 2, 3);

性能问题

arguments 只在两种情况下不会被创建,一是在函数内部被声明为局部变量,二是当做函数的形参。其他情况,arguments 对象总是会被创建。
由于 getter 和 setter 方法总是会随着 arguments 对象的创建而创建,因此使用 arguments 对性能本身几乎没有影响。
然而,有一种情形会严重影响 Javascript 的性能,那就是使用 arguments.callee。

复制代码 代码如下:

function foo() {
    arguments.callee; // do something with this function object
    arguments.callee.caller; // and the calling function object
}
function bigLoop() {
    for(var i = 0; i         foo(); // Would normally be inlined...
    }
}

在上述代码中,foo 函数不再是一个简单的内联扩展,因为它需要知道它自身以及它的调用者(caller)。这不仅抵消了内联扩展所带来的性能提升,同时也破坏了函数的封装性,因为函数本身可能需要依赖于一个特定的调用背景。
因此,建议大家尽量不要使用 arguments.callee。

以上就是关于Javascript arguments 对象的全部内容了,小伙伴们是否了解透彻呢,简单的说

arguments指函数的参数对象(指实际传入的参数)
arguments.length指函数的参数对象的长度
arguments[i]指第i个参数的值(第一个为0)

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!