js-basic

????

function debounce(fn,delay){
    let timer = null;
    return function(){
        if(timer){
            clearTimeout(timer)
        }

        timer = setTimeout(() => {
            fn.apply(this,arguments)
            timer = null
        },delay)
    }
}

// ??
input1.addEventListener('keyup',debounce(e => {
    console.log(input1.value)
},600))

????

function throttle(fn,delay){
    let timer = null;
    return function(){
        if(timer) return;
        timer = setTimeout(() => {
            fn.apply(this,arguments)
            timer = null;
        },delay)
    }
}

// ??
div1.addEventListener('arag',e => {
  console.log(e.offsetX)
})

???

  • ????
    let obj1 = {
    a: '1',
    b: 2,
    c: {
      d: 'xx'
    },
    e: ['1','2']
    }
    

let obj2 = obj1;
obj2.c.d = ‘yy’
obj2.e[0] = ‘3’
console.log(obj1.c.d) // yy
console.log(obj1.e[0]) // 3

+ ????obj2??????obj1??????
+ ??????????????
```js
// ???
function deepClone(obj = {}){
  // obj ? null ???????????????
  if(typeof obj !== 'object' || typeof == null){
    return obj;
  }

  let res;
  // ???????
  if(obj instanceof Array){
    res = []
  }else{
    res = {}
  }

  for(let key in obj){
    // ?? key ???????
    if(obj.hasOwnProperty(key)){
      // ???????
      res[key] = deepClone(obj[key])
    }
  }
  // ????
  return res;
}

????loadsh isEqual

// ??????????
function isObject(obj){
  return typeof obj === 'object' && obj !== null
}

function isEqual(obj1,obj2){
  if(!isObject(obj1) || !isObject(obj2)){
    // ?????
    return obj1 === obj2
  }
  // ??????
  if(obj1 === obj2 ){
    return true;
  }
  // ???????????????
  // 1. ??? obj1 ? obj2 ? keys ?????
  const obj1Keys = Object.keys(obj1)
  const obj2Keys = Object.keys(obj2)
  if(obj1Keys.length !== obj2Keys.length){
    return false;
  }
  // 2. ? obj1 ????? obj2 ??????
  for(let key in obj1){
    // ???? key ? val �� ?????
    const res = isEuqal(obj1[key],obj2[key])
    if(!res){
      return false;
    }
  }
  // 3. ???
  return true;
}

??promise??????

function loadImg(url){
    return new Promise((resolve,reject) => [
        let img  = document.createElement(img)

        img.onload = () => {
            resolve(img)
        }

        img.onerror = () => {
            reject(new Error('err'))
        }
        img.src = url;
    ])
}

// ??
const url1 = '';
const url2 = '';
 loadImg(url1).then(img1 => {
     console.log(img1.width)
     return img1 // ????
 }).then(img1 => {
     console.log(img1.height)
     return loadImg(url2) // promise ??
 }).then(img2 => {
     console.log(img2.width)
     return img2
 }).then(img2 => {
     console.log(img2.height)
 }).catch(ex => console.error(ex))

??10?a??? ?????????

let i , a;
for(i = 0 ;i < 10; i++ ){
    a = document.createElement('a');
    a.innerHTML = i + '<br />';
    a.addEventListener('click', e => {
        e.preventDefault();
        alert(i)
    })
    document.body.appendChild(a)
}

??bind

Function.prototype.mybind = function(){
    const args = Array.prototype.slice.call(arguments)
    const t = args.shift()

    const self = this;
    return function(){
        return self.apply(t,args)
    }
}

// ??
function fn1(a, b, c) {
    console.log('this', this)
    console.log(a, b, c)
    return 'this is fn1'
}

const fn2 = fn1.bind1({x: 100}, 10, 20, 30)
const res = fn2()
console.log(res)

????ajax

function ajax(url){
    return new Promise((resolve,reject) => {
        let xhr = new XMLHttpRequest()
        xhr.open('get',url,true)
        xhr.onreadystatechange= function(){
            if(xhr.readystate === 4){
                if(xhr.status === 200){
                    resolve(xhr.responseText)
                }else if(xhr.status === 400){
                    reject(new Error('404'))
                }
            }
        }
    })
}

// ??
ajax(url),then(res => console.log(res))

????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 ele = this[i]
            fn(ele)
        }
    }
    on(type,fn){
        return this.each(ele => {
            ele.addEventListener(type,fn,false)
        })  
    }
    // ???? DOM API
}

// ??
jQuery.prototype.dialog = function(info){
    alert(info)
}

// ???
class myJquery extends jQuery {
    constructor(selector){
        super(selector)
    }
    // ???????
    addClass(className){

    }
    style(data){

    }
}

?url?????js??

function fn(){
  const obj = {}
  let val = window.location.search.substr(1);
  val.split('&').forEach(item => {
    const arr = item.split('=');
    res[arr[0]] = arr[1]
  })
  return obj;
}

function fn(){
  const obj = {};
  const pList = new URLSearchParams(location.search)
  pList.forEach((val,key) => {
    obj[key] = val
  })
  return obj
}

????flatern

function flat(arr){

  const isDeep = arr.some(item => item instanceof Array)
  if(!isDeep) return arr;

  const res = Array.prototype.concat.apply([],arr)
  return flat(res)
}

?????trim???????????

// ?????trim???????????
String.prototype.trim = function(){
  return this.replace(/^\s+/,'').replace(/\s+$/,'')
}

?????????????

// ?????????????
function max(){
  const nums = Arrat.prototype.slice.call(arguments)
  let max = 0;
  nums.forEach(item => {
    if(item>max){
      max = item
    }
  })
  return max;
}

??

????


   转载规则


《js-basic》 朝飞 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录