call 和 apply 都是为了改变某个函数运行时的 context 即上下文而存在的,换句话说,就是为了改变函数体内部 this 的指向。
call 和 apply二者的作用完全一样,只是接受参数的方式不太一样。
方法定义
apply
Function.apply(obj,args)方法能接收两个参数:
obj:这个对象将代替Function类里this对象
args:这个是数组或类数组,apply方法把这个集合中的元素作为参数传递给被调用的函数。
立即学习“Java免费学习笔记(深入)”;
call
call方法与apply方法的第一个参数是一样的,只不过第二个参数是一个参数列表
在非严格模式下当我们第一个参数传递为null或undefined时,函数体内的this会指向默认的宿主对象,在浏览器中则是window
var test = function(){
console.log(this===window);
}
test.apply(null);//true
test.call(undefined);//true用法
"劫持"别人的方法
此时foo中的logName方法将被bar引用 ,this指向了bar
var foo = {
name:"mingming",
logName:function(){
console.log(this.name);
}
}
var bar={
name:"xiaowang"
};
foo.logName.call(bar);//xiaowang实现继承
function Animal(name){
this.name = name;
this.showName = function(){
console.log(this.name);
}
}
function Cat(name){
Animal.call(this, name);
}
var cat = new Cat("Black Cat");
cat.showName(); //Black Cat在实际开发中,经常会遇到this指向被不经意改变的场景。
有一个局部的fun方法,fun被作为普通函数调用时,fun内部的this指向了window,但我们往往是想让它指向该#test节点,见如下代码:
window.id="window";
document.querySelector('#test').onclick = function(){
console.log(this.id);//test
var fun = function(){
console.log(this.id);
}
fun();//window
}使用call,apply我们就可以轻松的解决这种问题了
window.id="window";
document.querySelector('#test').onclick = function(){
console.log(this.id);//test
var fun = function(){
console.log(this.id);
}
fun.call(this);//test
}当然你也可以这样做,不过在ECMAScript 5的strict模式下,这种情况下的this已经被规定为不会指向全局对象,而是undefined:
window.id="window";
document.querySelector('#test').onclick = function(){
var that = this;
console.log(this.id);//test
var fun = function(){
console.log(that.id);
}
fun();//test
}function func(){
"use strict"
alert ( this ); // 输出:undefined
}
func();以上就是javascript改变函数体内部指向的apply与call用法实例详解的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号