[英]How to deal with fn.call(this) replacing original this
首先,我有一个用于管理员工的应用程序。 当用户创建应用程序的新实例时,我希望他们可以选择提交一个功能,该功能将在应用程序中的其他任何功能之前运行。 问题是我需要在该功能的末尾添加功能,因此我需要将其传递回应用程序。
但是,如果我在StateManager.js
类中使用fn.call(this)
,则它将覆盖状态管理器的this
并摆脱StateManager
的功能。 返回的确切错误是Uncaught TypeError: this.onPreload is not a function
本质上,当创建一个新实例时,我想使用用户的preload
功能,并将其传递给StateManager.js
,在此处对其进行调整。
这是演示代码:
class Application { constructor(options = {}) { return new User(options); } } class User { constructor(options) { this._options = options; this.state = new StateManager(this); this.job = new Job(this); this.init(); } init() { this.state.onPreload = this._options.preload; this.state.preload.call(this); } } class Job { constructor(user) { this.user = user; } changeTitle(title) { this.user.jobTitle = title; } } class StateManager { constructor(user) { this.user = user; this.onPreload = null; } preload() { this.onPreload(); } } const options = { preload: preload }; const app = new Application(options); function preload() { app.job.changeTitle('CEO'); }
index.js
import { Application } from './Application.js';
const options = {
preload: preload
};
const app = new Application(options);
function preload() {
// Access some irrelevant function in job that sets a new value
app.job.changeTitle('CEO');
}
app.js
import { User } from './User.js';
export class Application {
constructor(options = {}) {
return new User(options);
}
}
user.js的
import { StateManager } from './StateManager.js';
import { Job } from './Job.js';
export class User {
constructor(options = {}) {
this._options = options;
this.state = new StateManager(this);
this.job = new Job(this);
this.init();
}
init() {
this.state.onPreload = this._options.preload;
this.state.preload.call(this);
}
}
statemanager.js
export class StateManager {
constructor(user) {
this.user = user;
this.onPreload = null;
}
preload() {
this.onPreload();
// My custom functionality to add at the end.
}
}
preload()
指的是全局变量app
,但首先是在用于初始化app
的函数中调用了它。 它需要接收正在初始化的User
对象,而不是引用全局变量。
使用this.state.onPreload = this._options.preload.bind(this);
将preload
功能的上下文绑定到该对象。
您也可以更改StateManager.preload()
以使用this.onPreload.call(this.user);
。 但这可能会导致不适当地的依赖关系,并不能在所有情况下都适用。 如果我更好地理解了所有关系,则也许可以更好地做出决定。
class Application { constructor(options = {}) { return new User(options); } } class User { constructor(options) { this._options = options; this.state = new StateManager(this); this.job = new Job(this); this.init(); } init() { this.state.onPreload = this._options.preload.bind(this); this.state.preload(); } } class Job { constructor(user) { this.user = user; } changeTitle(title) { this.user.jobTitle = title; } } class StateManager { constructor(user) { this.user = user; this.onPreload = null; } preload() { this.onPreload(); } } const options = { preload: preload }; const app = new Application(options); console.log(app.jobTitle); function preload() { this.job.changeTitle('CEO'); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.