// main.js —— this 的四种调用形式与优先级 // 所有结论都在模块(严格模式)下取得;非严格模式会把 undefined 换成 globalThis。 export const obj = { name: 'obj', getName() { return this === undefined ? 'undefined' : this.name; }, }; function Person(name) { this.name = name; } export function defaultBinding() { const detached = obj.getName; return detached(); // 严格模式下 this 是 undefined } export function implicitBinding() { return obj.getName(); // this 是 obj } export function explicitBinding() { const target = { name: 'explicit' }; return { call: obj.getName.call(target), apply: obj.getName.apply(target), bind: obj.getName.bind(target)(), }; } export function newBinding() { const p = new Person('Ada'); return { name: p.name, isInstance: p instanceof Person }; } export function newBeatsBind() { function Who() { this.name = this.name || 'new-target'; } const Bound = Who.bind({ name: 'bound-context' }); return new Bound().name; // new 忽略 bind 绑定的 this } export function bindBeatsImplicit() { function who() { return this.name; } const bound = who.bind({ name: 'bound' }); const holder = { name: 'holder', who: bound }; return holder.who(); // 隐式调用不能覆盖已绑定的 this } export function arrowThisIsLexical() { const captured = this; // 普通调用时为 undefined(模块是严格模式) const arrow = () => this; return { calledWithOther: arrow.call({ other: true }) === captured, capturedIsUndefined: captured === undefined, }; } export function arrowCannotBeConstructed() { const Arrow = () => {}; try { new Arrow(); return '没有抛错'; } catch (e) { return e.constructor.name; // TypeError } } export function run(log = console.log) { const rows = [ ['默认绑定:脱离对象调用', defaultBinding()], ['隐式绑定:obj.getName()', implicitBinding()], ['显式绑定:call / apply / bind', JSON.stringify(explicitBinding())], ['new 绑定', JSON.stringify(newBinding())], ['优先级:new > bind', newBeatsBind()], ['优先级:bind > 隐式', bindBeatsImplicit()], ['箭头函数忽略 .call 的 this', JSON.stringify(arrowThisIsLexical())], ['箭头函数不能 new', arrowCannotBeConstructed()], ]; log('场景 => 结果'); for (const [label, value] of rows) log(`${label} => ${value}`); log('-'.repeat(50)); log('要点:this 由调用点决定(箭头函数除外)。优先级:new > 显式 bind > 隐式 obj.f() > 默认。'); return rows; }