重构new
function _new ( FC , ... args) {
if ( typeof FC !== 'function' ) throw new TypeError ( '参数1必须是函数' )
if ( ! FC . prototype) throw new TypeError ( '参数1不能是箭头函数' )
let obj = Object. create ( FC . prototype)
let ret = FC . apply ( obj, args)
console. log ( ret)
if ( ret !== null && / object|function / i . test ( typeof ret) ) {
return ret
}
return obj
}
重构bind
Function . prototype. myApply = function ( Ctx, args ) {
if ( ! Array. isArray ( args) ) throw new TypeError ( '参数2必须是数组' )
Ctx = Ctx == null ? window : ( typeof Ct != 'object' ? Object ( Ctx) : Ctx)
const methodName = Symbol ( )
Ctx[ methodName] = this
let ret = Ctx[ methodName] ( ... args)
delete Ctx[ methodName]
return ret
}
function fn1 ( a, b, c, d, e ) {
console. log ( this , a, b, c, d, e)
return '你的姓名为:' + this . name
} ;
var obj = { name: 2222 , fn: 'abc' } ;
console. log ( fn1. myApply ( obj, [ 1 , 2 , 3 , 4 , 5 ] ) )
Bind
Function . prototype. myBind = function ( Ctx, ... args1 ) {
const func= this
return function ( ... args2) {
func . apply ( Ctx, [ ... args1, ... args2] )
}
}
instanceof
function _instanceof ( obj, FC ) {
if ( typeof obj != 'object' ) throw new TypeError ( '必须是引用' )
if ( typeof obj === 'function' && obj == null ) throw false
let prototype = FC . prototype
if ( ! prototype) return false
if ( typeof Symbol === 'function' ) {
var insFn = FC [ Symbol. hasInstance]
if ( typeof insFn === 'function' ) {
return insFn . call ( FC , obj)
}
}
var proto = Object. getPrototypeOf ( obj)
while ( 1 ) {
if ( proto === null ) return false
if ( proto === prototype) return true
proto = Object. getPrototypeOf ( proto)
}
}
forEach
Array . prototype. _forEach = function ( fn, thisArg ) {
if ( typeof fn !== 'function' ) throw '参数必须是函数'
let arr = this
for ( let i = 0 ; i < arr. length; i++ ) {
fn . call ( thisArg, arr[ i] , i, arr)
}
}
window. value = 0
let obj = { value: 1 }
let arr = [ "_" , "for" , "each" ]
let arr1= [ 1 , 2 , 3 , 4 ]
arr. _forEach (
function ( ele, index, arr ) {
console. log ( "ele, index, arr" , ele, index, arr) ;
console. log ( "this.vaule" , this . value) ;
} , obj)
map
Array . prototype. _map = function ( fn, thisArg ) {
if ( typeof fn !== 'function' ) throw '参数必须是函数'
if ( ! Array. isArray ( thisArg) ) throw '只能数组使用'
const arr = this
const newArr = [ ]
for ( let i = 0 , len = arr. length; i < len; i++ ) {
newArr. push ( fn . call ( thisArg, arr[ i] , i, arr) )
}
return newArr
}
reduce
function array_reduce ( arr, fn, initValue ) {
if ( arr. length= 0 ) return
if ( arr. length=== 1 ) return arr[ 0 ]
var index= 1
var value= arr[ 0 ]
if ( initValue!== undefined ) {
index= 0 ; value= initValue
}
for ( ; index< arr. length; index++ ) {
value= fn ( valeu, arr[ index] , index, arr)
}
return value
}