- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试找到一种在 ES6 中创建类似抽象类的方法。到目前为止,我尝试的每件事总是会遇到语言和/或其语法的限制(也是我对原型(prototype)制作的有限了解)。
基本 oop;我们声明一个类并扩展它。最终类必须访问其父类(super class)中的一些字段和方法,但不是全部。它还改变了公共(public)方法...
类声明应该是完美的封装,所以除了这段代码之外没有其他东西能够到达它(类似于命名空间的东西)。
到目前为止,我在 ES5 中的实验是错误的...我非常感谢您的建议和帮助。
(function(){
// ==================================
function AbstractClass(params) {
var _myParams = params;
var _privateField = "Only AbstractClass can see me";
this.publicField = "Everybody can see me";
function privateFunc() {
// Does private stuff
}
}
AbstractClass.prototype.publicFunc = function() {
// Does public stuff
privateFunc(); // Works?
}
// ==================================
function FinalClass(params) {
// How to pass the params to the superclass?
}
FinalClass.prototype.publicFunc = function() {
// Override and calls the superclass.publicFunc()?
// How can I touch _privateField ? publicField ?
}
FinalClass.prototype = Object.create(AbstractClass.prototype);
// ==================================
var foo = new FinalClass("hello world!");
foo.publicFunc();
})();
你能告诉我这段代码有什么问题以及如何解决吗?
额外问题:如何在 ES6 中正确执行此操作?
三重红利: protected 领域和方法呢?
谢谢。
最佳答案
这实际上是一个很好的问题,我会尽量给你一个有见地的答案......
正如我已经在 Stack Overflow 的某处解释过的那样,JavaScript 并不是真正的基于类的语言。它基于原型(prototype)。这是一个完全不同的编程范例,您应该考虑到这一点。因此,当您使用 Vanilla JS 编写内容时,通常最好忘记(只是一点点)您对 Java 或 C++ 的了解。
但是,JavaScript 是一种非常灵活的语言,您可以按照自己的意愿进行编程。在我看来,JavaScript 编程主要有两种风格:惯用 风格和经典 风格。
你想要的是一个抽象类。抽象类是不能实例化的类,只能用作派生类的模型。如果你关心严格的封装,这就是你如何在 ES5 中实现它:
// ==============================
// ABSTRACT "CLASS"
// ==============================
var OS = (function (n) {
// Here "name" is private because it is encapsulated in the IIFE
var name = "";
// Constructor
function OS (n) {
// If "OS" is called with "new", throw an error
if (this.constructor === OS) {
throw new Error('You cannot instantiate an abstract class!');
}
name = n;
}
// We cannot call this method directly (except with "call" or "apply") because we cannot have direct instances of "OS"
OS.prototype.boot = function () {
return name + ' is booting...';
};
// This is an abstract method. It will be in the prototype of derived objects but should be overriden to work
OS.prototype.shutdown = function () {
throw new Error('You cannot call an abstract method!');
};
// Getter for "name"
OS.prototype.getName = function () {
return name;
};
// The constructor must be returned to be public
return OS;
})();
// ==============================
// CONCRETE "CLASS"
// ==============================
var LinuxDistro = (function (name) {
// Constructor
function LinuxDistro(name) {
// Here we call the constructor of "OS" without "new", so there will not be any error
OS.call(this, name);
}
// Here "Linux Distro" inherits from "OS"
LinuxDistro.prototype = Object.create(OS.prototype);
LinuxDistro.prototype.constructor = LinuxDistro;
// Private function/method
function textTransform(str, style) {
return style === 'lowercase' ? str.toLowerCase() : str.toUpperCase();
}
// The parent method is used and overriden
LinuxDistro.prototype.boot = function () {
return OS.prototype.boot.call(this) + ' Welcome to ' + textTransform(this.getName());
};
// The abstract method is implemented
LinuxDistro.prototype.shutdown = function () {
return 'Shutting down... See you soon on ' + textTransform(this.getName());
};
// The constructor must be returned to be public
return LinuxDistro;
})();
// ==============================
// CLIENT CODE
// ==============================
var arch = new LinuxDistro('Arch Linux');
console.log(arch.getName());
console.log(arch.boot());
console.log(arch.shutdown());
现在你想用 ES6 做同样的事情。好处是 ES6 提供了很好的语法糖来处理类。同样,如果您关心严格封装,则可以采用以下实现:
// ==============================
// ABSTRACT "CLASS"
// ==============================
const OS = (n => {
// Here "name" is private because it is encapsulated in the IIFE
let name = "";
class OS {
constructor(n) {
// If "OS" is called with "new", throw an error
if (new.target === OS) {
throw new Error('You cannot instantiate an abstract class!');
}
name = n;
}
// We cannot call this method directly (except with "call" or "apply") because we cannot have direct instances of "OS"
boot() {
return `${name} is booting...`;
}
// This is an abstract method. It will be in the prototype of derived objects but should be overriden to work
shutdown() {
throw new Error('You cannot call an abstract method!');
}
// Getter for "name"
get name() {
return name;
}
}
// The class must be returned to be public
return OS;
})();
// ==============================
// CONCRETE "CLASS"
// ==============================
const LinuxDistro = (name => {
// Private function/method
function textTransform(str, style) {
return style === 'lowercase' ? str.toLowerCase() : str.toUpperCase();
}
class LinuxDistro extends OS {
constructor(name) {
// Here we call the constructor of "OS" without "new", so there will not be any error
super(name);
}
// The parent method is used and overriden
boot() {
return `${super.boot()} Welcome to ${textTransform(this.name)}`;
}
// The abstract method is implemented
shutdown() {
return `Shutting down... See you soon on ${textTransform(this.name)}`;
}
}
// The class must be returned to be public
return LinuxDistro;
})();
// ==============================
// CLIENT CODE
// ==============================
const arch = new LinuxDistro('Arch Linux');
console.log(arch.name); // This is not a direct access to "name". The getter is used...
console.log(arch.boot());
console.log(arch.shutdown());
当然,这些片段并不完美,可能看起来有点吓人。但由于 JavaScript 的原型(prototype)性质,我认为这是我们能做的最好的事情。
您可能已经看到,类成员要么是私有(private)的(由于 IIFE 和闭包),要么是公共(public)的(由于对象的创建方式,具有自己的属性和原型(prototype)链)。如果你真的想要 protected 成员,这是另一回事......
当您为 JavaScript 代码考虑 OOP 模型时,我建议您使用 TypeScript .这比上面提供的代码更方便、可读和可维护。
最后,如果您想更进一步,了解如何在 JavaScript 中实现所有传统的 OOP 设计模式(尤其是 GoF 模式),我邀请您看一下我在 GitHub 上的一个项目:PatternifyJS
关于javascript - 使用私有(private)/ protected /公共(public)字段和方法扩展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43081398/
这个问题在这里已经有了答案: How to make a property protected AND internal in C#? (8 个答案) 关闭 9 年前。 我需要声明一个既受又 内部保
我有以下代码: class Base{ protected val alpha ="Alpha"; protected def sayHello = "Hello"; } class
我正在尝试运行一个宏来创建一个工作正常的pdf。 Excel 文件获得签名后,Excel 文件将自动受到保护。 问题:我的工作表上有一个按钮,需要按下该按钮才能创建 pdf 文档网。然而,这是无法完成
子类需要能够使用种子随机数生成器。 使用的优点和缺点是什么 public abstract class AbstractClass { protected Random rnd; public
我们有两个类(class)(A 和 B)。 A类只能由继承它的类创建(A类)B 类可以由用户创建。 A 类,版本 1 有一个private 数据成员,并且有方法访问 A 类中的数据。 A 类,版本 2
当父类受到保护时,我对继承类的默认构造函数有疑问,在我看来,子类也会有一个默认构造函数受到保护,但事实并非如此。 除了在子类上强制默认构造函数外,还有其他方法可以强制保护默认构造函数吗? C++11
我有一个抽象类,我想在其 protected 构造函数中初始化一个只读字段。我希望这个只读字段在派生类中可用。 按照我将所有字段设为私有(private)并公开属性的习惯,我实现如下: abstrac
我在运行大数据时遇到错误。错误已由以下示例示例解释 加载数据 mdata <- as.matrix(read.table('https://gubox.box.com/shared/static
我在获取 时遇到问题非法访问错误 对于以下示例: 我在名为 arch 的 gradle 模块中声明了一个基类 abstract class BaseClass { protected abst
我相信通过 实现 JSF 应用程序的安全性+ + & 通过使用 是两种不同的方式!?他们是吗? 我尝试通过上述第一种方法(使用 + + )来实现安全性,但发现使用 protected 和不
有没有办法确定以下的二传手能见度差异: public Prop { get; protected set; } protected Prop { get; set; } 使用反射?还是那些与 C# 反
我读了一本关于 OOP 的书,并且关于“ protected ”访问修饰符的示例对我来说很奇怪。 例子总结 这个例子是为了测试“protected”保留字对变量的影响。 ClassA 有 2 个 pr
内部——在集会上公开,在其他地方私有(private)。 protected - 只有派生类可以访问父类成员。 Protected internal - protected OR internal -
我有一个类代表 Wicket 中带有“返回”、“前进”和“取消”按钮的基本页面。但并非所有页面都有所有按钮,例如。 G。第一页明显没有“返回”。 我的想法是定义一个通用的ActionHandler p
在了解到嵌套类是嵌套类的成员并因此可以完全访问嵌套类的成员这一事实后(至少对于 C++11,请参见 here),我在尝试创建嵌套类模板: #include using namespace std;
我刚刚使用了 Resharper,并一直在尝试将字段转换为属性。我希望这些属性受到保护,但 Resharper 不想给我这个选项。相反,只有一个 protected 内部选项。这让我思考。要么某处有一
这是 question 的扩展一个小时前问过。 当覆盖派生类中的虚方法时,我们不能修改访问修饰符。考虑 System.Web.UI 命名空间中的 Control 类 public class Cont
有人可以解释一下 C# 中 protected 和 protected internal 修饰符之间的区别吗?看起来他们的行为是相同的。 最佳答案 “protected internal”访问修饰符是
我想知道下面两行代码之间是否有区别: protected $var = null; protected $var; 我已经看到两者都被使用了,我想知道这是否只是一个偏好问题,(也就是 $var; 将变
我正在尝试使用mockito为“另存为”操作编写单元测试。该操作的一部分是制作并显示一个文件对话框,用户可以在其中输入要保存的文件。选择文件不是我可以自动化的操作,因此我想模拟 FileDialog
我是一名优秀的程序员,十分优秀!