var player = function (e) {
return (function f(m) {
return m ? (function (n) {
return $('#Player', n).get(0) || f($('iframe', n).get(0));
})(m.contentWindow.document) : null;
})($(e).get(0));
};
這段碼涉及函數表達式、立即執行函數(IIFE)、遞迴、jQuery/DOM 物件轉換等進階概念。要真正看懂它,必須先建立對 JS 函數本質的清晰認知:函數是第一級物件,可賦值、傳參、回傳、動態建立。
// 函數宣告(提升 hoisted)
function foo() { return 1; }
// 函數表達式(不提升)
var bar = function() { return 2; };
var baz = function foo() { return 3; }; // 具名函數表達式,foo 僅在函數內部可見
(function() { /* 程式碼 */ })(); // 寫法一
(function() { /* 程式碼 */ }()); // 寫法二
// 用途:建立私有作用域、避免汙染全域、模組化封裝
function higherOrder(fn) {
return fn(10); // 接收函數並調用
}
higherOrder(function(x) { return x * 2; }); // 20
function factory() {
return function(x) { return x + 1; }; // 回傳函數
}
var inc = factory();
inc(5); // 6
var player = function (e) {
// 1. $(e).get(0) → 取得原生 DOM 元素
// 2. 傳入 IIFE,參數 m = DOM 元素
return (function f(m) {
// 3. 若 m 存在(非 null/undefined)
return m ? (function (n) {
// 4. n = m.contentWindow.document(iframe 內文檔)
// 5. 在 n 中找 #Player,取 DOM 節點;找不到則遞迴進 iframe
return $('#Player', n).get(0) || f($('iframe', n).get(0));
})(m.contentWindow.document) : null;
})($(e).get(0)); // IIFE 立即執行,傳入外層參數 e 對應的 DOM
};
等價重寫(去除遞迴、展開 IIFE):
var findDoc = function (n) {
return $('#Player', n).get(0) || findX($('iframe', n).get(0));
};
var findX = function (m) {
return m ? findDoc(m.contentWindow.document) : null;
};
var player = function (e) {
return findX($(e).get(0));
};
| 呼叫模式 | this 指向 | 範例 |
|---|---|---|
| 函數呼叫 | 全域物件(非嚴格模式)/ undefined(嚴格模式) | fn() |
| 方法呼叫 | 呼叫該方法的物件 | obj.method() |
| 建構子呼叫 | 新建立的實例物件 | new Fn() |
| call/apply/bind | 指定的第一個參數 | fn.call(obj, ...) |
var obj = {
method: function() {
console.log(this); // obj
function inner() {
console.log(this); // window/undefined —— 非預期!
}
inner();
}
};
解法:var self = this; / 箭頭函數 () => {} / inner.call(this) / bind。
param = {})不影響外部原物件。JavaScript 函數是第一級物件,支援高階函數、閉包、IIFE、遞迴等強大模式。掌握函數建立方式、呼叫模式決定 this、參數按值共享三大核心,即能輕鬆閱讀並撰寫如開頭所示的進階函數式程式碼。