1.获取url参数值
< script >
var url = 'https://www.baidu.com/s?id=123&name=why&phone=13876769797' ;
function getQueryString ( name ) {
var str = '' ; / / 用来存储参数的字符串
var index = url . indexOf ( '?' ) ; / / 获取参数索引
/ / 判断链接是否有参数
if ( index = = = - 1 ) {
return undefined
}
str = url . substring ( index + 1 ) . split ( '&' ) ;
for ( let i = 0 ; i < str . length ; i + + ) {
var splitItem = str [ i ] . split ( '=' ) ; / / [ key ,value ]
console . log ( splitItem ) ;
if ( splitItem [ 0 ] = = name ) {
return splitItem [ 1 ] ;
}
}
}
console . log ( getQueryString ( 'phone' ) ) ; / / 13876769797
< / script >
2.手写setInterval 方法
function selfSetInterval ( callback , interval ) {
var timer = null ;
var now = Date . now ; / / 获取 1970 年 1 月 1 日截止到当前时刻的时间戳
var startTime = now ( ) ; / / 定时器开始时间时间戳
var endTime = '' ;
var loop = function ( ) {
timer = requestAnimationFrame ( loop ) ;
endTime = now ( ) ; / / 当前时间时间戳
if ( endTime - startTime > = interval ) {
startTime = endTime ; / / 重置开始时间时间戳
callback & & callback ( timer ) ; / / 执行回调方法
}
}
timer = requestAnimationFrame ( loop ) ;
return timer ;
}
/ / 测试
var count = 0 ;
selfSetInterval ( function ( timer ) {
console . log ( '定时器测试---' , timer )
count + + ;
if ( count > = 3 ) {
cancelAnimationFrame ( timer ) ; / / 取消requestAnimationFrame ( ) 方法的动画帧请求
}
} , 1000 )
3、手写call 、apply 和 bind
Function . prototype . selfCall = function ( context ) {
if ( typeof this ! = = 'function' ) {
throw new TypeError ( 'error' ) ;
}
const symbolFn = Symbol ( ) ;
context = context | | window ;
context [ symbolFn ] = this ;
var args = [ ...arguments ] . slice ( 1 ) ;
var result = context [ symbolFn ] ( . . . args ) ;
delete context [ symbolFn ] ;
return result ;
}
function foo ( ) {
console . log ( this . age ) ;
}
var obj = {
age : 18 ,
name: 'fxl'
}
foo ( ) / / undefined
foo . selfCall ( obj ) ; / / 18 将this指向obj
Function . prototype . selfApply = function ( context ) {
if ( typeof this ! = = 'function' ) {
throw new TypeError ( 'error' ) ;
}
context = context | | window ;
context . fn = this ;
var result = arguments [ 1 ] ? context . fn ( . . . arguments [ 1 ] ) : context . fn ( ) ;
delete context . fn ;
return result ;
}
function foo ( ) {
console . log ( this . age ) ;
}
var obj = {
age : 18 ,
name: 'fxl'
}
foo ( ) / / undefined
foo . selfApply ( obj ) ;
Function . prototype . selfBind = function ( context ) {
if ( typeof this ! = = 'function' ) {
throw TypeError ( 'error' ) ;
}
const self = this ;
const args = [ ...arguments ] . slice ( 1 ) ;
return function F ( ) {
if ( this instanceof F ) {
return new self ( . . . args , . . . arguments ) ;
}
return self . apply ( context , args . concat ( . . . arguments ) ) ;
}
}
function foo ( ) {
console . log ( this . age ) ;
}
var obj = {
age : 18 ,
name: 'fxl'
}
foo ( ) / / undefined
var newF = foo . selfBind ( obj ) ;
newF ( ) ;