如何一次手写到快乐,JavaScript手写实现深拷贝、bind、jQuery
1. 手写深拷贝函数
function deepClone ( obj = { } ) {
if ( typeof obj !== 'object' || obj == { } ) {
return obj
}
let result
if ( obj instanceof Array ) {
result = [ ]
} else {
result = { }
}
for ( let key in obj) {
if ( obj. hasOwmproperty ( key) ) {
result[ key] = deepClone ( obj[ key] )
}
}
return result
}
2. 利用apply手写一个bind函数
Function. prototype. bindNew = function ( ) {
const args = Array. prototype. slice. call ( arguments)
const that = args. shift ( )
const self = this
return function ( ) {
return self. apply ( that, args)
}
}
3. 手写简单的jQuery,需要考虑插件和扩展性。
class jQuery {
constructor ( selector) {
const result = document. querySelectorAll ( selector) ;
const length = result. length;
for ( let i = 0 ; i < length; i++ ) {
this [ i] = result[ i] ;
}
this . length = length;
this . selector = selector;
}
get ( index) {
return this [ index] ;
}
each ( fn) {
for ( let i = 0 ; i < this . length; i++ ) {
const elem = this [ i] ;
fn ( elem) ;
}
}
on ( type, fn) {
return this . each ( ( elem) => {
elem. addEventListener ( type, fn, false ) ;
} ) ;
}
}
jQuery. prototype. dialog = function ( info) {
alert ( info) ;
} ;
class myJQuery extends jQuery {
constructor ( selector) {
super ( selector) ;
}
addClass ( className) {
this . each ( ( elem) => elem. classList. add ( className) ) ;
}
style ( data) {
this . each ( ( elem) => elem. classList. add ( style) ) ;
}
}