javascript - ES5 类中的 JavaScript 原型继承范围
问题描述
我正在尝试为 Angular 编写 XMLHttpRequest 拦截器,但我不能简单地使用 HttpInterceptor,因为我需要拦截使用 XMLHttpRequest API 的第三方库。
整体波纹管解决方案有效,但我搞砸了在类中定义原型的范围。另外,如果我使用箭头函数,它就不会出现。
export class Interceptor {
constructor(private config) {
const XMLHttpRequestOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function (method, url) {
if (url === this.config.url) { // this.config is out of scope of class
this.onreadystatechange = function() {
this.setRequestHeader('Authorization', 'Bearer ...');
};
}
return XMLHttpRequestOpen.apply(this, arguments);
};
}
}
欢迎任何简洁的解决方案。
解决方案
将稍后要访问的值存储在不是 的属性的变量中this
,这样它就不会在重新绑定时丢失。
export class Interceptor {
constructor(private config) {
const XMLHttpRequestOpen = window.XMLHttpRequest.prototype.open;
const configUrl = this.config.url;
window.XMLHttpRequest.prototype.open = function (method, url) {
if (url === configUrl) {
this.onreadystatechange = function() {
this.setRequestHeader('Authorization', 'Bearer ...');
};
}
return XMLHttpRequestOpen.apply(this, arguments);
};
}
}
推荐阅读
- amazon-web-services - ECS部署及匹配运行任务数
- airflow - 使用 KubernetesPodOperator 测试气流 dag
- javascript - 如何动态更改 React 组件的样式
- kibana - 上传任意 XYZ 坐标来开发我自己的非地球地图?
- javascript - 更新一个字段以进一步嵌套在文档中 - MongoDB/Node
- python - 根据值数组在数据框中过滤
- javascript - 使用 Apollo 客户端和 React 自定义 useMutation 钩子
- javascript - Typescript : Es6 Map TS Type Relation
- windows - 如何从键盘/宏键盘发送“SendMessage”?
- mysql - 如何检查插入触发器中的字段是否为空?