gpt4 book ai didi

javascript - 使用bind修改Angular Controller 内的 "this"

转载 作者:行者123 更新时间:2023-11-28 19:13:41 25 4
gpt4 key购买 nike

我正在使用 Angular 新的路由器组件和 js。我有多个 Controller ,如下所示。

我想做的是为所有 Controller 应用一个函数,我不需要在每个 Controller 上都这样做吗?

function HomeController (authService, factoryClient) {
console.log ('this is home controller');
this = doCommonController.bind(this); //generates an error
//here this should contain currentUser, authService, logout and testVar
console.log(this);
}

其功能是:

var doCommonController = function (authService, currentUser) {
this.testVar = 'value';
this.authService = authService;
this.currentUser = currentUser;
this.logout = this.authService.logout;
}

另外,如何从 Controller 传递 authServicefactoryClient 以便在 doCommonController 中可用?

最佳答案

您需要使用 .call() 而不是 .bind(),也不要为 this 分配任何值这是无效的

function HomeController(authService, factoryClient) {
console.log('this is home controller');
var currentUser;
doCommonController.call(this, authService, currentUser); //generates an error
//here this should contain currentUser, authService, logout and testVar
console.log(this);
}

关于javascript - 使用bind修改Angular Controller 内的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30303760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com