方法与调用形式
跳转到“方法与调用形式”对象的可调用属性可用作方法,但普通函数的 this 由调用形式决定,并非永远绑定在定义时的对象上。xiaoming.age() 这种调用把接收者作为 this;把函数取出后调用则有不同规则。以下年份相减只是粗略年数,不考虑生日:
const xiaoming = { name: '小明', birth: 1990, age() { return new Date().getFullYear() - this.birth; }};xiaoming.age; // 函数对象xiaoming.age(); // 运行时当前年份减1990,不应写死为25。| 概念/用法 | 说明 | 代码示例 |
|---|---|---|
| 对象方法 | 普通方法调用的接收者成为this | const person = {birth: 1990, age() { return 2024 - this.birth; }}; |
| this关键字 | 下例使用固定2024年,不是当前精确年龄 | person.age(); // 34 |
| this的指向 | 独立普通调用:严格函数为undefined,非严格函数通常为全局对象 | function getAge() { return 2024 - this.birth; } |
| 修复this | 嵌套函数通过变量捕获外层this | const captured = {birth: 1990, age() { const that = this; function read() { return 2024 - that.birth; } return read(); }}; |
| apply | 接收this及类数组参数集合 | getAge.apply(person, []); // 34 |
| call | 接收this及逐个参数 | getAge.call(person); // 34 |
| 函数包装 | 用包装函数添加行为,不等同于@decorator语法 | const countedParseInt = (...args) => { count++; return oldParseInt(...args); }; |
表中例子需按所示依赖准备;包装示例还需 let count = 0; const oldParseInt = parseInt;,它不覆盖全局内置函数。
方法取出后为何可能失效?
在严格模式函数中,独立调用的 this 为 undefined;非严格函数的独立调用通常使用全局对象。在浏览器普通脚本中全局对象通常为 window,但不能把这个结论直接套用到模块、Node.js或箭头函数。'use strict' 必须位于脚本或函数的指令序言,中途放一行字符串不会追溯地开启严格模式。
'use strict';function getAgeStrict() { return 2024 - this.birth; }const methodPerson = { birth: 1990, age: getAgeStrict };console.log(methodPerson.age()); // 34const detached = methodPerson.age;try { detached(); } catch (error) { console.log(error.name); } // TypeError
const nested = { birth: 1990, age() { function readBirth() { return 2024 - this.birth; } return readBirth(); }};try { nested.age(); } catch (error) { console.log(error.name); } // TypeError
const fixed = { birth: 1990, age() { const that = this; function readBirth() { return 2024 - that.birth; } return readBirth(); }};console.log(fixed.age()); // 34;也可用嵌套箭头函数捕获外层this。显式控制普通函数的this
不必只用 obj.method()。call / apply 为这次调用提供接收者,bind 返回绑定后的新函数。箭头函数的this来自外层,不能用这些方法改绑。
function getAge() { return 2024 - this.birth; }const receiver = { birth: 1990 };getAge.apply(receiver, []); // 34getAge.call(receiver); // 34const boundAge = getAge.bind(receiver);boundAge(); // 34apply 接受数组或类数组对象,call 接受逐个实参;展开语法则需要可迭代对象,两者并不完全相同。对于不读取this的 Math.max 可以传 null:
Math.max.apply(null, [3, 5, 4]); // 5Math.max.apply(null, {0: 3, 1: 5, 2: 4, length: 3}); // 5Math.max.call(null, 3, 5, 4); // 5普通函数若依赖this,不能笼统把它设为null;非严格函数还会把null/undefined转换成全局对象。