如何处理 fn.call(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');
}

索引.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');
}

应用.js

import { User } from './User.js';
export class Application {
constructor(options = {}) {
return new User(options);
}
}

用户.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);
}
}

状态经理.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');
}

最新更新