1. call
Function.prototype.myCall = function(context = window, ...args) {
if (typeof this !== 'function') {
throw new TypeError('not funciton')
}
context = context || window;
context.fn = this;
const result = context.fn(...args);
delete context.fn;
return result;
}
2. apply
Function.prototype.myApply = function(context = window, args = []) {
if (typeof this !== 'function') {
throw new TypeError('not funciton')
}
context = context || window;
context.fn = this;
const result = context.fn(...args);
delete context.fn;
return result;
}
3. bind
Function.prototype.myBind = function(context, ...args) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
const _this = this;
return function Bind(...newArgs) {
if (this instanceof Bind) {
return _this.myApply(this, [...args, ...newArgs])
}
return _this.myApply(context, [...args, ...newArgs])
}
}
4. instanceof原理
function instanceOf(example, classFunc) {
let proto = Object.getPrototypeOf(example)
let classFuncPrototype = classFunc.prototype
while (true) {
if (proto = null) {
return false
}
if (proto = classFuncPrototype) {
return true
}
proto = Object.getPrototypeOf(proto)
}
}
5. new的本质
function myNew (fun) {
return function () {
let obj = {
proto : fun.prototype
}
fun.call(obj, ...arguments)
return obj
}
}
function person(name, age) {
this.name = name
this.age = age
}
let obj = myNew(person)('chen', 18)
6. promise
class Promise {
constructor (fn) {
this.state = 'pending'
this.value = undefined
this.reason = undefined
let resolve = value => {
if (this.state = 'pending') {
this.state = 'fulfilled'
this.value = value
}
}
let reject = value => {
if (this.state = 'pending') {
this.state = 'rejected'
this.reason = value
}
}
try {
fn(resolve, reject)
} catch (e) {
reject(e)
}
}
then(onFulfilled, onRejected) {
switch (this.state) {
case 'fulfilled':
onFulfilled()
break
case 'rejected':
onRejected()
break
default:
}
}
}
7. 基本的深拷贝
let obj = {a: 1, b: {x: 3}}
JSON.parse(JSON.stringify(obj))
function deepClone(obj) {
let copy = obj instanceof Array ? [] : {}
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
copy[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
}
}
return copy
}
8. 用setTimeout模拟setInterval
setTimeout (function () {
setTimeout (arguments.callee, 500)
}, 500)
9. 继承
function Child () {
Parent.call(this)
}
(function () {
let Super = function () {}
Super.prototype = Parent.prototype
Child.prototype = new Super()
})()
10. 基本的Event Bus
class EventEmitter {
constructor () {
this.events = this.events || new Map()
}
addListener (type, fn) {
if (!this.events.get(type)) {
this.events.set(type, fn)
}
}
emit (type) {
let handle = this.events.get(type)
handle.apply(this, [...arguments].slice(1))
}
}
let emitter = new EventEmitter()
emitter.addListener('ages', age => {
console.log(age)
})
emitter.emit('ages', 18)
11. 双向数据绑定
let obj = {}
let input = document.getElementById('input')
let span = document.getElementById('span')
Object.defineProperty(obj, 'text', {
configurable: true,
enumerable: true,
get() {
console.log('获取数据了')
},
set(newVal) {
console.log('数据更新了')
input.value = newVal
span.innerHTML = newVal
}
})
input.addEventListener('keyup', function(e) {
obj.text = e.target.value
})
完整实现:
https:
12. 简单路由
class Route{
constructor(){
this.routes = {}
this.currentHash = ''
this.freshRoute = this.freshRoute.bind(this)
window.addEventListener('load', this.freshRoute, false)
window.addEventListener('hashchange', this.freshRoute, false)
}
storeRoute (path, cb) {
this.routes[path] = cb || function () {}
}
freshRoute () {
this.currentHash = location.hash.slice(1) || '/'
this.routesthis.currentHash
}
}
13. rem实现原理
function setRem () {
let doc = document.documentElement
let width = doc.getBoundingClientRect().width
let rem = width / 75
doc.style.fontSize = rem + 'px'
}
addEventListener("resize", setRem)
14. 节流函数
function throttle (fn, delay) {
let prev = Date.now()
return function () {
let context = this
let arg = arguments
let now = Date.now()
if (now - prev >= delay) {
fn.apply(context, arg)
prev = Date.now()
}
}
}
function fn () {
console.log('节流')
}
addEventListener('scroll', throttle(fn, 1000))
15. 防抖函数
function debounce (fn, delay) {
let timer = null
return function () {
let context = this
let arg = arguments
clearTimeout(timer)
timer = setTimeout(function () {
fn.apply(context, arg)
}, delay)
}
}
function fn () {
console.log('防抖')
}
addEventListener('scroll', debounce(fn, 1000))
16. 基于promise实现 AJAX
function ajax (options) {
const url = options.url
const method = options.method.toLocaleLowerCase() || 'get'
const async = options.async
const data = options.data
const xhr = new XMLHttpRequest()
if (options.timeout && options.timeout > 0) {
xhr.timeout = options.timeout
}
return new Promise ((resolve, reject) => {
xhr.ontimeout = () => reject && reject('请求超时')
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
resolve && resolve(xhr.responseText)
} else {
reject && reject()
}
}
}
xhr.onerror = err => reject && reject(err)
let paramArr = []
let encodeData
if (data instanceof Object) {
for (let key in data) {
paramArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
}
encodeData = paramArr.join('&')
}
if (method = 'get') {
const index = url.indexOf('?')
if (index = -1) url += '?'
else if (index !== url.length -1) url += '&'
url += encodeData
}
xhr.open(method, url, async)
if (method === 'get') xhr.send(null)
else {
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8')
xhr.send(encodeData)
}
})
}
17. 实现懒加载
<ul>
<li><img src="./imgs/default.png" data="./imgs/1.png" alt=""></li>
<li><img src="./imgs/default.png" data="./imgs/2.png" alt=""></li>
<li><img src="./imgs/default.png" data="./imgs/3.png" alt=""></li>
<li><img src="./imgs/default.png" data="./imgs/4.png" alt=""></li>
<li><img src="./imgs/default.png" data="./imgs/5.png" alt=""></li>
<li><img src="./imgs/default.png" data="./imgs/6.png" alt=""></li>
<li><img src="./imgs/default.png" data="./imgs/7.png" alt=""></li>
<li><img src="./imgs/default.png" data="./imgs/8.png" alt=""></li>
<li><img src="./imgs/default.png" data="./imgs/9.png" alt=""></li>
<li><img src="./imgs/default.png" data="./imgs/10.png" alt=""></li>
</ul>
let imgs = document.querySelectorAll('img')
// 可视区高度
let clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
function lazyLoad () {
// 滚动卷去的高度
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
for (let i = 0; i < imgs.length; i ++) {
// 图片在可视区冒出的高度
let x = clientHeight + scrollTop - imgs[i].offsetTop
// 图片在可视区内
if (x > 0 && x < clientHeight+imgs[i].height) {
imgs[i].src = imgs[i].getAttribute('data')
}
}
}
// addEventListener('scroll', lazyLoad) or setInterval(lazyLoad, 1000)