网站建设好公司,做网站用html5,站长seo计费系统,青岛建站seo公司call, apply, 和 bind 方法都是通过改变函数的执行上下文#xff08;this#xff09;来实现改变 this 的。 1. call 方法 call 方法#xff1a;call 方法通过将函数作为对象的方法调用#xff0c;并传递一个新的上下文对象作为第一个参数来改变函数的执行上下文。函数内部可… call, apply, 和 bind 方法都是通过改变函数的执行上下文this来实现改变 this 的。 1. call 方法 call 方法call 方法通过将函数作为对象的方法调用并传递一个新的上下文对象作为第一个参数来改变函数的执行上下文。函数内部可以通过 this 引用该新的上下文对象。
实现示例 Function.prototype.call function(context, ...args) {context context || window; // 如果上下文对象未提供则默认为全局对象浏览器中为 windowconst key Symbol(fn); // 创建一个唯一的键以避免覆盖上下文对象中的现有属性context[key] this; // 将函数作为对象的方法添加到上下文对象中const result context[key](...args); // 调用函数delete context[key]; // 删除添加的方法属性return result; // 返回函数执行结果
};// 使用示例
const person {name: Alice,greet: function(message) {console.log(${message}, ${this.name}!);}
};const otherPerson {name: Bob
};person.greet.call(otherPerson, Hello); // 输出Hello, Bob!2. apply 方法 apply 方法apply 方法与 call 方法类似不同之处在于它接受一个参数数组而不是逐个列出参数。参数数组中的每个元素都会作为参数传递给函数。
实现示例 Function.prototype.apply function(context, args) {context context || window; // 如果上下文对象未提供则默认为全局对象浏览器中为 windowconst key Symbol(fn); // 创建一个唯一的键以避免覆盖上下文对象中的现有属性context[key] this; // 将函数作为对象的方法添加到上下文对象中const result context[key](...args); // 调用函数并将参数数组展开传递delete context[key]; // 删除添加的方法属性return result; // 返回函数执行结果
};// 使用示例
const person {name: Alice,greet: function(message) {console.log(${message}, ${this.name}!);}
};const otherPerson {name: Bob
};person.greet.apply(otherPerson, [Hello]); // 输出Hello, Bob!3. bind 方法 bind 方法bind 方法返回一个新函数并预先绑定了指定的执行上下文。新函数被调用时它的执行上下文将是预先绑定的上下文对象。
实现示例 Function.prototype.bind function(context, ...args) {const fn this; // 当前函数return function(...innerArgs) {return fn.call(context, ...args, ...innerArgs); // 调用原始函数并传递绑定的上下文和参数};
};// 使用示例
const person {name: Alice,greet: function(message) {console.log(${message}, ${this.name}!);}
};const otherPerson {name: Bob
};const greetBob person.greet.bind(otherPerson);
greetBob(Hello); // 输出Hello, Bob!4. 区别
4.1 call 方法 call 方法允许你显式地调用一个函数并指定函数执行时的上下文this。除了第一个参数是要绑定的上下文对象之外它可以接受任意数量的参数作为要传递给函数的参数。
示例 const person {name: Alice,greet: function(message) {console.log(${message}, ${this.name}!);}
};const otherPerson {name: Bob
};person.greet.call(otherPerson, Hello); // 输出Hello, Bob!4.2 apply 方法 apply 方法与 call 方法类似但它接受一个参数数组而不是逐个列出参数。数组中的每个元素都会被作为参数传递给函数。
示例 const person {name: Alice,greet: function(message) {console.log(${message}, ${this.name}!);}
};const otherPerson {name: Bob
};person.greet.apply(otherPerson, [Hello]); // 输出Hello, Bob!4.3bind 方法 bind 方法不会立即调用函数而是返回一个新函数新函数的执行上下文this被绑定为指定的上下文对象。bind 方法可以预先绑定函数的上下文并返回一个新的函数以后可以在需要时调用。
示例 const person {name: Alice,greet: function(message) {console.log(${message}, ${this.name}!);}
};const otherPerson {name: Bob
};const greetBob person.greet.bind(otherPerson);
greetBob(Hello); // 输出Hello, Bob!4.4 总结
call 和 apply 方法可以立即调用函数并指定执行上下文不同之处在于参数的传递方式。bind 方法返回一个新函数预先绑定了执行上下文并可以在需要时调用。call 和 apply 是直接调用函数而 bind 是创建一个新函数。call 和 apply 可以传递参数列表而 bind 只能传递执行上下文。