apply
作用:改變this執(zhí)行,函數(shù)立即執(zhí)行,參數(shù)以數(shù)組傳遞
思路:
? ? ? ? 1、在this新指向的對象上,增加一個(gè)函數(shù)等于待執(zhí)行函數(shù)
? ? ? ? 2、去參數(shù)
? ? ? ? 3、執(zhí)行函數(shù)
? ? ? ? 4、刪除增加的函數(shù),返回結(jié)果
// 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 (參數(shù)以數(shù)組形式在第二個(gè)參數(shù)傳遞, 立即執(zhí)行)
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; // 將函數(shù)綁定到當(dāng)前上下文中
result = context.fn(...arguments[1]); //取得第二個(gè)參數(shù)(數(shù)組)并展開傳給函數(shù)
delete context.fn; // 刪除新增的函數(shù)
return result;
}
call
作用:改變this執(zhí)行,函數(shù)立即執(zhí)行,參數(shù)依次傳遞
思路:
? ? ? ? 1、在this新指向的對象上,增加一個(gè)函數(shù)等于待執(zhí)行函數(shù)
? ? ? ? 2、取參數(shù)
? ? ? ? 3、執(zhí)行函數(shù)
? ? ? ? 4、刪除增加的函數(shù),返回結(jié)果
// 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 (參數(shù)依次展開, 立即執(zhí)行)
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; // 將函數(shù)綁定到當(dāng)前上下文中
result = context.fn(...[...arguments].slice(1)); //取得第除第一個(gè)參數(shù)之外的參數(shù)并展開傳給函數(shù)
delete context.fn; // 刪除新增的函數(shù)
return result;
}
bind
作用:改變this執(zhí)行,返回一個(gè)函數(shù),參數(shù)依次傳遞
思路:
? ? ? ? 1、指定一個(gè)函數(shù)等于當(dāng)前函數(shù)
? ? ? ? 2、返回一個(gè)新函數(shù)文章來源:http://www.zghlxwxcb.cn/news/detail-464249.html
? ? ? ? 3、函數(shù)中使用apply立即執(zhí)行函數(shù)文章來源地址http://www.zghlxwxcb.cn/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 (參數(shù)依次展開,不立即執(zhí)行)
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, // 因?yàn)榉祷氐暮瘮?shù),防止new執(zhí)行,所以判斷一下,如果是new出來的執(zhí)行this環(huán)境下的,如果不是就是新上下文環(huán)境下的
args.concat(...arguments)
)
}
}
到了這里,關(guān)于手寫apply、call、bind的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!