JavaScript 中 this 的绑定规则
前端JavaScript
默认绑定(普通函数调用)
function foo() { console.log(this); } foo(); // 浏览器中是 window,严格模式下是 undefine
隐式绑定(作为对象方法调用)
const obj = { name: 'Alice', greet() { console.log(this.name); } }; obj.greet(); // 输出 'Alice',this 指向 ob
显式绑定(call / apply / bind)
function say() { console.log(this.name); } const person = { name: 'Bob' }; say.call(person); // 输出 'Bob' say.apply(person); // 输出 'Bob' const boundSay = say.bind(person); boundSay(); // 输出 'Bob
new 绑定(构造函数)
function Person(name) { this.name = name; } const p = new Person('Charlie'); console.log(p.name); // 输出 'Charlie'
箭头函数(继承外层 this)
const obj = { name: 'David', arrowFunc: () => { console.log(this.name); }, regularFunc() { const arrow = () => { console.log(this.name); }; arrow(); } }; obj.arrowFunc(); // 通常是 undefined 或全局对象的 name,因为箭头函数没有自己的 this obj.regularFunc(); // 输出 'David',箭头函数继承了 regularFunc 的 this 指向 obj