西安制作公司网站的公司,清理wordpress,wordpress背景怎么改,权威发布高清图片先看1个重要原则#xff1a; 由Vue管理的函数#xff0c;一定不要写箭头函数#xff0c;箭头函数的this就不再是Vue实例了 箭头函数的 this 指向在定义时确定#xff0c;继承自外层作用域#xff08;即定义时的上下文#xff09;的 this#xff0c;且无法通过 call、app…先看1个重要原则 由Vue管理的函数一定不要写箭头函数箭头函数的this就不再是Vue实例了 箭头函数的 this 指向在定义时确定继承自外层作用域即定义时的上下文的 this且无法通过 call、apply 或 bind 改变。以下是关键点总结
1. 词法作用域的 this 箭头函数没有自己的 this它使用外层非箭头函数作用域的 this 值。若外层没有函数则指向全局对象如 window 或 global。 示例 const obj {value: 42,getValue: function() {// 普通函数中的 this 指向 objconst arrowFn () this.value;return arrowFn();}
};
console.log(obj.getValue()); // 输出 42 2. 与普通函数的区别 普通函数this 由调用方式决定如对象方法、构造函数、事件监听等。 箭头函数this 固定为定义时的外层 this。 示例对比 // 普通函数this 指向调用者
const obj1 {value: 10,fn: function() { console.log(this.value); }
};
setTimeout(obj1.fn, 100); // 输出 undefinedthis 指向全局// 箭头函数this 继承外层
const obj2 {value: 10,fn: function() {setTimeout(() console.log(this.value), 100); // 继承外层 thisobj2}
};
obj2.fn(); // 输出 10 3. 无法通过绑定方法修改 使用 call、apply 或 bind 无法改变箭头函数的 this。 示例 const outerThis { name: Outer };
const arrowFn () console.log(this.name);
arrowFn.call({ name: New }); // 输出 Outer若外层 this 指向全局则可能输出 undefined 4. 对象字面量中的陷阱 对象字面量不创建作用域内部箭头函数的 this 指向全局。 示例 const obj {value: Hello,getValue: () console.log(this.value) // this 指向全局如 window
};
obj.getValue(); // 输出 undefined假设外层为全局 5. 在构造函数中的行为 箭头函数作为构造函数会报错不能 new。 但若在构造函数内定义箭头函数会继承实例的 this function Person() {this.age 0;setInterval(() {this.age; // this 指向 Person 的实例}, 1000);
}
const p new Person(); // age 每秒自增 6.总结 箭头函数的 this继承自定义时的外层作用域且不可更改。 使用场景需要固定 this 时如回调、事件处理、setTimeout。 避免场景需要动态 this 时如对象方法、构造函数。 通过理解箭头函数的词法 this 特性可以更灵活地控制代码中的上下文绑定。