// main.js —— 箭头函数的 this 是词法的:定义时捕获,调用时不可改 // 因此箭头适合做回调,不适合做对象方法。 export function arrowKeepsOuterThis() { const obj = { value: 42, viaArrow() { return [1, 2].map(() => this.value).join(','); }, viaRegular() { return [1, 2].map(function () { return this.value; }).join(','); }, }; let regular; try { regular = obj.viaRegular(); } catch (e) { regular = e.constructor.name; } return { arrow: obj.viaArrow(), regular }; } export function arrowAsMethod() { const obj = { value: 1, get: () => this.value, // this 来自模块顶层,是 undefined }; try { return obj.get(); } catch (e) { return e.constructor.name; } } export function capturedAtDefinition() { const make = function () { return { ctx: this, arrow: () => this }; }; const ctx = { id: 'ctx' }; const o = make.call(ctx); return { same: o.arrow() === ctx, id: o.arrow().id }; } export function run(log = console.log) { const r1 = arrowKeepsOuterThis(); const r3 = capturedAtDefinition(); const rows = [ ['map 里的箭头函数', r1.arrow], ['map 里的普通函数(丢 this)', r1.regular], ['箭头函数当对象方法', arrowAsMethod()], ['箭头函数在定义时捕获 this', `${r3.same} / ${r3.id}`], ]; log('场景 => 结果'); for (const [label, value] of rows) log(`${label} => ${value}`); log('-'.repeat(50)); log('要点:箭头函数没有自己的 this,取定义位置外层的 this;所以它不能当方法,也不能被 call/apply/bind 改变。'); return rows; }