跳转到内容
新建笔记

JavaScript 方法

对象的可调用属性可用作方法,但普通函数的 this 由调用形式决定,并非永远绑定在定义时的对象上。xiaoming.age() 这种调用把接收者作为 this;把函数取出后调用则有不同规则。以下年份相减只是粗略年数,不考虑生日:

const xiaoming = {
name: '小明',
birth: 1990,
age() { return new Date().getFullYear() - this.birth; }
};
xiaoming.age; // 函数对象
xiaoming.age(); // 运行时当前年份减1990,不应写死为25。
概念/用法说明代码示例
对象方法普通方法调用的接收者成为thisconst person = {birth: 1990, age() { return 2024 - this.birth; }};
this关键字下例使用固定2024年,不是当前精确年龄person.age(); // 34
this的指向独立普通调用:严格函数为undefined,非严格函数通常为全局对象function getAge() { return 2024 - this.birth; }
修复this嵌套函数通过变量捕获外层thisconst 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()); // 34
const 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, []); // 34
getAge.call(receiver); // 34
const boundAge = getAge.bind(receiver);
boundAge(); // 34

apply 接受数组或类数组对象,call 接受逐个实参;展开语法则需要可迭代对象,两者并不完全相同。对于不读取this的 Math.max 可以传 null:

Math.max.apply(null, [3, 5, 4]); // 5
Math.max.apply(null, {0: 3, 1: 5, 2: 4, length: 3}); // 5
Math.max.call(null, 3, 5, 4); // 5

普通函数若依赖this,不能笼统把它设为null;非严格函数还会把null/undefined转换成全局对象。

参考:MDN:this、Function.apply。