商务网站建设需要备案吗,做外贸的女生干净吗,企业名录搜索软件app,佛山网站建设冯哥call和apply的用途是完全一样的。改变函数中this的指向#xff1a; 为什么要改变this的指向呢#xff1f;这个有什么用#xff1f;有哪些场景呢#xff1f; 首先this的指向总是在变的#xff0c;this的指向是由函数执行时所在的环境决定的#xff0c;而不是函数声明时的环…call和apply的用途是完全一样的。改变函数中this的指向 为什么要改变this的指向呢这个有什么用有哪些场景呢 首先this的指向总是在变的this的指向是由函数执行时所在的环境决定的而不是函数声明时的环境。 this都指向哪里 1、在控制台中输入下面的代码此时可以看到this指向a这个对象。 var a{name:a,getName:function(){return this.name;}
}
console.info(a.getName());//a 2、此时this指向了window window.name window;
var a{name:a,getName:function(){return this.name;}
}var b a.getName;
console.info(b());//window 结论 如果函数是作为一个对象的属性被调用的用点的方式调用此时函数内的this就指向这个对象。 如果是用变量或者名称的方式直接调用的不是使用点调用则指向window。 场景 this的改变在写代码时经常会遇到这种情况将函数作为回调函数使用时this的指向变为了window这个不是我们预期的结果 window.namewindow;
var a{name:a,getName:function(callback){return callback();//funcB使用非对象.的方式调用},funcB:function(){return this.name;}
}
console.info(a.getName(a.funcB));//window 这个时候就可以用call或者apply把this传递到callback中callback中的this的指向就会被传入的this所替代。 当然也可以传入其他对象覆盖当前this的指向。 window.namewindow;
var b{name:b
};
var a{name:a,getName:function(callback){return callback.call(b);//传入b},funcB:function(){return this.name;}
}
console.info(a.getName(a.funcB));//b 也可以借用这个对象的方法。 window.namewindow;
var b{name:b, getBName:function(){return this.name;}
};
var a{name:a,getName:function(callback){return callback.call(b);//传入b},funcB:function(){return this.getBName();}
}
console.info(a.getName(a.funcB));//b 使用这个功能可以实现类似继承的效果 var Ffunction(name){this.name name;
}
var S function(){this.agearguments[1];F.apply(this,arguments);
}
S.prototype.getNameAndAgefunction(){console.info(名字是this.name年龄是this.age);
}var s new S(小红,9岁);
s.getNameAndAge();//名字是小红年龄是9岁 call和apply的区别 传入的参数形式不一样 call(obj参数1参数2) apply(obj[参数1参数2])转载于:https://www.cnblogs.com/panyujun/p/9367911.html