zoukankan      html  css  js  c++  java
  • JavaScript Function.apply() 函数详解

    语法

    functionObject.apply( [ thisObj [, argsArray ]] )

    apply()函数用于调用当前函数functionObject,并可同时使用指定对象thisObj作为本次函数执行时函数内部的this指针引用。

    该函数属于Function对象,所有主流浏览器均支持该函数。

    参数

    参数描述
    thisObj 可选/Object类型指定执行functionObject函数时,函数内部this指针引用的对象。
    argsArray 可选/Array|argumens对象调用functionObject函数时所传入的参数数组或arguments对象

    如果提供了argsArray参数,则该参数必须是一个数组,或者arguments对象。数组中的每个元素(arguments对象中的每个属性0...n)将按照顺序作为参数传入该函数。

    如果提供了argsArray参数,则必须提供thisObj参数。

    备注:该函数与Function对象的call()函数作用相同,只不过call()函数是将Function对象的参数一个个分别传入,apply()函数是将Function对象的参数以一个数组或arguments对象的形式整体传入。

    返回值

    apply()方法的返回值为任意类型,其返回值取决于当前functionObject对象的返回值。

    示例&说明

    name = "张三";
    age = 18;
    
    function test(){
        document.writeln(this);
        document.writeln(this.name);
        document.writeln(this.age);     
    };
    
    // 全局函数内部的this默认为全局对象window
    test(); // [object Window] 张三 18
    
    
    var obj = {name: "李四", age: 20};
    // 更改内部的this指针引用对象为obj
    test.apply(obj); // [object Object] 李四 20
    
    
    function foo(a, b){
        document.writeln(this.name);    
        document.writeln(a);    
        document.writeln(b);    
    }
    // 改变this引用为obj,同时传递两个参数
    foo.apply(obj, [12, true]); // 李四 12 true
    
    
    function bar(){
        var o = {name: "王五"};
        // 调用foo()函数,并改变其this为对象o,传入当前函数的参数对象arguments作为其参数
        foo.apply(o, arguments);    
    }
    bar("CodePlayer", "www.365mini.com"); // 王五 CodePlayer www.365mini.com
  • 相关阅读:
    在列表中添加序号列
    在C#中使用正则表达式
    Git
    Linux 配置Java环境
    讯飞语义理解 JAVA SDK
    分屏显示
    Gdiplus
    重启进程
    MFC 常用功能属性
    MFC 打印
  • 原文地址:https://www.cnblogs.com/dehuachenyunfei/p/6650581.html
Copyright © 2011-2022 走看看