1. 實現一個call函數
// 將要改變this指向的方法掛到目標this上執行并返回
Function.prototype.call = function(context) {
if( typeof this !== 'function') {
throw new TypeError('not function')
}
context = context || window
context.fn = this
let arg = [...arguments].slice(1)
let result = context.fn(...arg)
delete context.fn
return result
}
2. 實現一個apply函數
Function.prototype.apply = function(contex) {
if( typeof this !== 'function') {
throw new TypeError('not function')
}
context = context || window
context.fn = this
let result
if(argument[1]) {
result = context.fn(...argument[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
3. 實現一個bind函數
Function.prototype.bind = function(context) {
if( typeof this !== 'function') {
throw new TypeError('not function')
}
let _this = this
let arg = [...arguments].slice(1)
// 處理使用 new 的情況
return function F(){
if(this instanceof F) {
return new _this(...arg, ...arguments)
} else {
return _this.apply(context, arg.concat(...arguments))
}
}
}
4. instanceof原理
A instanceof B 用于判斷 A 的原型鏈中是否有 B 的存在,相當于右邊 B 的變量原型是否在左邊 A 的原型鏈上
// 右邊變量的原型存在于左邊變量的原型鏈上
function instanceof(left, right) {
let leftValue = left.__proto__
let rightValue = right.prototype
// 循環查找,找到返回
while (true) {
if(leftValue === null) {
return false
}
if(leftValue === rightValue) {
return true
}
leftValue = leftValue.__proto__
}
}
5. Object.create 原理
create 創建一個空對象,將傳入的參數作為創建后對象的原型
function create(obj) {
function F(){}
F.prototype = obj
return new F()
}
6. new 本質
new 是可以進行調用構造函數的 constructor
function