變量類型和計算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; }