apply
作用:改变this执行,函数立即执行,参数以数组传递
思路:
1、在this新指向的对象上,增加一个函数等于待执行函数
2、去参数
3、执行函数
4、删除增加的函数,返回结果
// apply
function applyTest() {
var person = {
fullName: function (city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName: "Bill",
lastName: "Gates"
}
console.log(person.fullName.myApply(person1, ["Oslo", "Norway"]));
}
// 手写applyTest (参数以数组形式在第二个参数传递, 立即执行)
Function.prototype.myApply = function (context) {
if (typeof this !== 'function') {
conole.error('this is not a function');
}
let result = null;
context = context || window;
context.fn = this; // 将函数绑定到当前上下文中
result = context.fn(...arguments[1]); //取得第二个参数(数组)并展开传给函数
delete context.fn; // 删除新增的函数
return result;
}
call
作用:改变this执行,函数立即执行,参数依次传递
思路:
1、在this新指向的对象上,增加一个函数等于待执行函数
2、取参数
3、执行函数
4、删除增加的函数,返回结果
// call
function callTest() {
var person = {
fullName: function (city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName: "Bill",
lastName: "Gates"
}
console.log(person.fullName.myCall(person1, "Oslo", "Norway"));
}
// 手写call (参数依次展开, 立即执行)
Function.prototype.myCall = function(context) {
if (typeof this !== 'function') {
console.error('this is not a function');
}
context = context || window;
let result = null;
context.fn = this; // 将函数绑定到当前上下文中
result = context.fn(...[...arguments].slice(1)); //取得第除第一个参数之外的参数并展开传给函数
delete context.fn; // 删除新增的函数
return result;
}
bind
作用:改变this执行,返回一个函数,参数依次传递
思路:
1、指定一个函数等于当前函数
2、返回一个新函数文章来源:https://www.toymoban.com/news/detail-464249.html
3、函数中使用apply立即执行函数文章来源地址https://www.toymoban.com/news/detail-464249.html
function bindTest() {
var person = {
fullName: function (city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName: "Bill",
lastName: "Gates"
}
console.log(person.fullName.myBind(person1, "Oslo", "Norway")());
}
// 手写bind (参数依次展开,不立即执行)
Function.prototype.myBind = function(context) {
if (typeof this !== 'function') {
console.error('this is not a function');
}
let args = [...arguments].slice(1),
fn = this;
return function Fn() {
return fn.apply(
this instanceof Fn ? this : context, // 因为返回的函数,防止new执行,所以判断一下,如果是new出来的执行this环境下的,如果不是就是新上下文环境下的
args.concat(...arguments)
)
}
}
到了这里,关于手写apply、call、bind的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!