我正在扩展一个模块,当我声明一些私有属性(例如method)时,我注意到了init(),发生此错误:
类型具有私有属性“ init”的单独声明
我知道造成这种情况的原因是,我在超类中有一个相同的方法,但是我不想因为在一个类中已经使用了一个我甚至不能访问它的名称而调用了不同的名称私人的!
我将方法声明为私有方法,正是为了避免这种情况。我不想重写它,但这不应该阻止我在另一个类中再次声明它。到底有什么意义?
我认为这样做的原因是javascript的原型性质。
考虑以下代码
class A {
public constructor() {
this.method();
}
private method() {
console.log("A");
}
}
class B extends A {
private method() {
console.log("B");
}
}
new B();
Run Code Online (Sandbox Code Playgroud)
您期望控制台将显示,"A"因为在类的ctor中A我们调用了私有方法,这意味着它不能被类覆盖(为此我们已经保护了)。
但是这段代码编译成:
var A = (function () {
function A() {
this.method();
}
A.prototype.method = function () {
console.log("A");
};
return A;
}());
var B = (function (_super) {
__extends(B, _super);
function B() {
_super.apply(this, arguments);
}
B.prototype.method = function () {
console.log("B");
};
return B;
}(A));
Run Code Online (Sandbox Code Playgroud)
(操场上的代码)
如您所见,method原型中B的被新功能覆盖,因此实际上控制台将显示"B"。
这是受保护而不是私有的行为,可能是因为不允许这样做。
在我看来,您有3种选择:
| 归档时间: |
|
| 查看次数: |
3151 次 |
| 最近记录: |