Function.apply()函数详解

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

 

posted @ 2022-03-29 15:57  前端白雪  阅读(411)  评论(0)    收藏  举报