typeof 無法區分 null/數組/對象,instanceof 受原型鏈與跨框架影響。推薦:
function typeOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
// typeOf([]) === 'array', typeOf(null) === 'null', typeOf(/re/) === 'regexp'
function Person(name) {
if (!(this instanceof Person)) {
return new Person(name); // 自動補 new
}
this.name = name;
}
// Person('Tom') 與 new Person('Tom') 效果一致
注意:若用 Parent.call(this) 繼承,需先將子構造函數的 prototype 指向父原型。
function createSomething() {
if (supportH5) {
createSomething = function() { /* H5 實現 */ };
} else {
createSomething = function() { /* 降級實現 */ };
}
return createSomething(); // 首次調用執行新函數
}
首次調用判斷後重寫自身,後續調用零判斷開銷。
this 永遠指向最終調用函數的對象。call/apply:立即執行並指定 this。bind:返回新函數,this 固定,不立即執行,適合回調傳遞。var obj = {x: 1};
function fn() { console.log(this.x); }
fn.call(obj); // 1
var bound = fn.bind(obj);
bound(); // 1
setTimeout(fn, 300) 意為「300ms 後將 fn 推入任務隊列」,若主線程忙碌,實際執行時間 ≥ 300ms。setInterval 可能導致回調堆積(若回調耗時 > 間隔)。function repeat(fn, interval) {
fn();
setTimeout(function() { repeat(fn, interval); }, interval);
}
function chunkProcess(arr, process, chunkSize, delay) {
var i = 0, len = arr.length;
function next() {
var end = Math.min(i + chunkSize, len);
for (; i < end; i++) process(arr[i]);
if (i < len) setTimeout(next, delay);
}
next();
}
// 用法:每 100ms 處理 100 條,中間讓出主線程響應 UI
高頻事件(resize、scroll、drag、mousemove)必須節流。
var i = 0, j = 1;
window.onresize = function() {
if (j++ % 2 === 0) console.log(i++);
};
function throttle(method, context) {
clearTimeout(method.tId);
method.tId = setTimeout(function() {
method.call(context);
}, 100);
}
// 使用:window.onresize = function() { throttle(handler, this); };
原理:頻繁觸發時不斷清除上一個定時器,只有間隔 ≥ 100ms 才真正執行。
var EventEmitter = {
events: {},
on: function(name, fn) { (this.events[name] || (this.events[name] = [])).push(fn); },
off: function(name, fn) { var arr = this.events[name]; if (arr) arr.splice(arr.indexOf(fn), 1); },
emit: function(name) {
var args = [].slice.call(arguments, 1);
(this.events[name] || []).forEach(function(fn) { fn.apply(null, args); });
}
};
// 用法
EventEmitter.on('data', function(x) { console.log('got', x); });
EventEmitter.emit('data', 123);
降低模塊耦合,實現發布/訂閱。
這 8 大技巧涵蓋了 JS 核心難點與性能優化要點,靈活運用能寫出更健壯、高效、可維護的代碼。