1. //apply 方法调用一个具有给定this值的函数,以及作为一个数组(或类似数组对象)提供的参数。 var obj = { name : 'linxin' } function func(firstName, lastName){ console.log(firstName + ' ' + this.name + ' ' + lastName); } func.apply(obj, ['A', 'B']); // A linxin B //func调用apply方法,第一个参数为obj,第一个参数为func所指定的对象,所以func指定obj //第二个参数为一个数组,即这个数组为func提供参数 //所以执行结果为 A linxin B 2. //call() 方法调用一个函数, 其具有一个指定的this值和分别地提供的参数(参数的列表)。 var obj = { name: 'linxin' } function func(firstName, lastName) { console.log(firstName + ' ' + this.name + ' ' + lastName); } func.call(obj, 'C', 'D'); // C linxin D //func调用call方法,第一个参数为obj,第一个参数为func所指定的对象,所以func指定obj //之后的参数为func提供参数 //所以执行结果为 C linxin D 3. var obj = {}; obj.log = console.log; obj.log.call(console, this); //Window //obj 为一个对象, obj 的 log 属性被赋予 console.log //因此 obj.log === console.log //因此 obj.log.call(console, this); 相当于 console.log.call(console, this); //因此 obj 指向 console, 即 console.log(this); //this 为 Window
JavaScript apply() call()的理解
最新推荐文章于 2021-08-26 16:33:50 发布