這篇文章主要介紹了Javascript實現call,bind,apply的代碼怎么寫的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Javascript實現call,bind,apply的代碼怎么寫文章都會有所收獲,下面我們一起來看看吧。
1.檢查當前調用的是否為函數
2.如果當前沒有傳入指向的this,則賦值為window
3.將fn指向當前調用的函數
4.獲取傳入的參數
5.將參數傳入fn進行調用
6.將對象上的fn刪除
7.返回結果
//普通call的實現
function hello(){
console.log('hello 我是'+this.name);
};
let person = {
name:'krys'
};
var name = 'liang';//只有var的變量屬于window
hello();// 'hello 我是liang'
hello.call(person);//'hello 我是krys'
hello.call();//'hello 我是liang'
let person2 = {
name:'lwl'
}
Function.prototype.mycall = function(context){
//不傳入參數的時候,默認為window
if(typeof this !== "function"){
throw new TypeError('Error');
}
context = context || window;
context.fn = this;//fn就是上面的hello方法
const args = [...arguments].slice(1);//第一個參數不要
const result = context.fn(...args);//把剩下的其他參數傳給hello
delete context.fn;
return result;
}
hello.mycall(person2);function getParams(){
console.log('我是',this.name,'獲取一些參數',...arguments);
}
let person3 = {
name:'hhh'
};
getParams.apply(person3,['hello','world'])
Function.prototype.myApply = function(context){
if(typeof this !== "function"){
throw new TypeError()
}
context = context || window;
context.fn = this;
let result;
if(arguments[1]){
//如果有傳入參數數組
console.log(arguments[1])
result = context.fn(...arguments[1]);
}else{
result = context.fn();
}
delete context.fn;
return result;
}
getParams.myApply({name:'llll'},['jjj','kkkk','llll']);function getParams(){
console.log('我是',this.name,'獲取一些參數',...arguments);
}
let person3 = {
name:'hhh'
};
let person4 = {
name:'tttt'
};
getParams.bind(person3,'hello','world')
getParams.bind(person4,'hello','world')('jjj','kkk');
Function.prototype.myBind = function(context){
if(typeof this !== "function"){
throw new TypeError()
}
context = context || window;
const _that = this;
const args = [...arguments].slice(1);
return function F(){
if(this instanceof F){
return new _that(...args,...arguments);//這里的arguments是上面的jjj kkk
}
return _that.apply(context,args.concat(...arguments));//這里的arguments是上面的jjj kkk
}
}
getParams.myBind({name:'llll'},'jjj','kkkk','llll')('hhhhllll');關于“Javascript實現call,bind,apply的代碼怎么寫”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“Javascript實現call,bind,apply的代碼怎么寫”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。