gpt4 book ai didi

Javascript 继承依赖于构造函数参数

转载 作者:行者123 更新时间:2023-12-03 10:17:35 25 4
gpt4 key购买 nike

我想在 Angular 中实现原型(prototype)继承,其中基本类型被定义为 Angular 值。问题是设置我的子类型原型(prototype)。假设这个简化的例子:

文件 1

angular.module("Test")
.value("BaseController", BaseController);

BaseController.$inject = [...];

function BaseController(...) {
...
}

BaseController.prototype.func = function () {
...
};

文件2

angular.module("Test")
.controller("ChildController", ChildController);

ChildController.$inject = ["BaseController", ...];

function ChildController(BaseController, ...) {
BaseController.call(this, ...);

// save reference for later
ChildController.base = BaseController;
...
}

// ERROR - Clearly why
ChildController.prototype = Object.create(BaseController.prototype);

// ERROR - instance properties aren't available on this level
ChildController.prototype = Object.create(ChildController.base.prototype);

继承

问题在于原型(prototype)是在构造函数实例化之前生成的。但在实例化构造函数之前,我无法引用 Angular 注入(inject)的 BaseController

我能想到解决这个问题的唯一方法是公开定义我的BaseController,这样我就可以在 Angular 将它注入(inject)到我的构造函数之前访问它。我不喜欢这样,因为我不能将我的代码放在函数闭包内,而且我还想尽可能多地使用 Angular 的功能,而不需要将常用的 Javascript 与 Angular 代码混合在一起。

主要问题

有没有什么方法可以通过将基本类型定义为 Angular 中的值(或其他)来使原型(prototype)继承工作?

最佳答案

此解决方案专门针对您的方法。您可以使用模块的 run block 来分配原型(prototype)。在文件 2 中添加以下内容:

angular.module("Test").run(function(BaseController) {
ChildController.prototype = Object.create(BaseController.prototype);
});

BaseController 被注入(inject)并可用于创建原型(prototype)。由于此代码在实例化任何 Controller 之前运行,因此您将获得原型(prototype)继承。

另请记住,ChildController.$inject 必须包含所有 BaseController.$inject

另一种方法是将BaseController附加到模块本身:

angular.module("Test").BaseController = BaseController;
...
ChildController.prototype = Object.create(angular.module("Test").BaseController.prototype);

代码仍然是私有(private)的,构造函数仍然只能通过模块访问。

您还可以寻找继承的替代方案。根据具体情况,分层 Controller 可能是一个可行的解决方案。

<div ng-controller="BaseController"><%-- Handle Generic stuff --%>
...
<div ng-controller="ChildController"><%-- Handle specific stuff --%>

关于Javascript 继承依赖于构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29799320/

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