我使用什么JavaScript模式从原型方法访问私有方法

What JavaScript pattern do I use to access private methods from a prototype method?

本文关键字:方法 原型 访问 有方法 模式 什么 JavaScript      更新时间:2023-09-26

我使用什么JavaScript模式来提供

  1. 原型上的公共方法
  2. 可以从#1调用的私有方法
  3. 私有变量

当试图从原型公共方法调用私有方法时,我发现的其他答案似乎返回undefined。

事实上,您无法从原型访问私有内容。

原型通过将一个对象作为上下文绑定到所有方法来工作,因此您可以使用this关键字来访问它

在面向对象编程中,您称之为私有的东西是在编译时解析的,以提示您试图访问的数据不应该在类外可读。但在运行时,此数据将以与其他属性相同的方式存储。

要让方法访问私有字段,您可以直接在实例上创建方法,而不是在原型上创建方法以允许它访问私有范围。这被称为特权方法。看看道格拉斯·克罗克福德的这篇文章。

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
}

像Typescript这样添加类和键入+隐私设置的语言将私有字段与公共字段一起存储。

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;
})();