变量类型和计算ajax
function deepClone (obj = {}) { if (typeof obj !== 'object' || obj == null){ // 不是对象或者数组, 直接返回 return obj; } let result; if (obj instanceof Array) { result = []; } else { result = {}; } for (let key in obj) { if (obj.hasOwnProperty(key)) { // 保证 key 不是原型的属性 //递归 result[key] = deepClone(obj[key]); } } return result; }
原型和原型链编程
实例与构造函数的原型之间有直接的联系,可是实例与构造函数之间没有。数组
原型链的顶端是object.prototype,其上定义的toString()、valueOf()、hasOwnProperty()。promise
实例的隐式原型引用的是对应构造函数的显式原型:children.__proto__ === Parent.prototype
浏览器
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插件 jQuery.prototype.dialog = function (info) { alert(info); } // 造轮子 class myJQuery extends jQuery { constructor(selector) { super(selector); } // 扩展本身的方法 addClass(className) { } style(data) { } }
做用域和闭包性能优化
function createCache() { const data = {}; // 闭包中的数据, 被隐藏, 不被外界访问 return { set: function(key, val) { data[key] = val; }, get: function(key) { return data[key]; } } } const c = createCache(); c.set('a', 100); console.log(c.get('a'));
Function.prototype.bind1 = function () { // **将参数列表拆解为数组 const args = Array.prototype.slice.call(arguments); // 获取this ( 数组第一项 ) const this1 = args.shift(); // fn1.bind( ... )中的 fn1 const self = this; // 返回一个函数 return function() { return self.apply(this1, args); }; }
Function.prototype.myCall = function (ctx, ...args) { if (typeof this !== 'function') { throw new Error('not a function') } let fn = Symbol(); ctx = ctx || window; ctx[fn] = this; ctx[fn](...args); delete ctx[fn]; } function fn1(a, b) { console.log(this.name); console.log(a, b); }
Function.prototype.myApply = function (ctx, args = []) { if (typeof this !== 'function') { throw new Error('not a function') } let fn = Symbol(); ctx = ctx || window; if(!(args instanceof Array)){ throw new TypeError('请输入数组做为参数'); } ctx[fn] = this; ctx[fn](...args); delete ctx[fn]; }
异步网络
function ajax(url) { const p = new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('get', url, true); xhr.onreadystatechange = function () { if(xhr.readyState === 4) { if(xhr.status === 200) { resolve( JSON.parse(xhr.responseText) ) } else if (xhr.status === 404) { reject(new Error('404 not found')) } } } xhr.send(null); }) return p; }