我应该使用什么样的JavaScript模式给我:
在试图从原型公共方法调用私有方法时,我发现的其他答案似乎没有定义。
发布于 2015-11-01 00:02:15
实际上,您不能从原型中访问一些私有的东西。
原型通过将对象绑定为所有方法的上下文来工作,因此您可以使用this关键字来访问它。
在面向对象编程中,您称之为私有的东西是在编译时解决的,它提示您尝试访问的数据不应该从类外部读取。但在运行时,这些数据将以与其他属性相同的方式存储。
要让方法访问私有字段,您可以直接在实例上创建方法,而不是在prototype上创建方法,以允许它访问私有范围。这被称为特权方法。请看道格拉斯·克罗克福德的这篇文章。
var ClassExample = function () {
var privateProperty = 42
this.publicProperty = 'Hello'
var privateMethod = function () {
return privateProperty
}
this.privilegedMethod = function () {
return privateProperty
}
}
ClassExample.prototype.publicMethod = function() {
return this.publicProperty
}添加类和类型+隐私设置的语言(如类型记录)在公共字段旁边存储私有字段。
class ClassExample {
private privateProperty
public publicProperty
constructor () {
this.privateProperty = 42
this.publicProperty = 'Hello'
}
method () {
return this.privateProperty
}
}将编译在
var ClassExample = (function () {
function ClassExample() {
this.privateProperty = 42;
this.publicProperty = 'Hello';
}
ClassExample.prototype.method = function () {
return this.privateProperty;
};
return ClassExample;
})();https://stackoverflow.com/questions/33457614
复制相似问题