gpt4 book ai didi

javascript - Private V.S. 令人困惑的例子 书中的公共(public)方法?

转载 作者:行者123 更新时间:2023-12-03 06:09:26 26 4
gpt4 key购买 nike

我最近一直在阅读 Stefanov 的《Javascript 模式》。我发现这个例子让我感到困惑:

Another case of using a convention to mimic functionality is the private members >con- vention. Although you can implement true privacy in JavaScript, sometimes >evelopers find it easier to just use an underscore prefix to denote a private >method or property. Consider the following example:

var person = {

getName: function () {

return this._getFirst() + ' ' + this._getLast(); },

_getFirst: function () {

// ... },

_getLast: function () {

// ... }

};

In this example getName() is meant to be a public method, part of the stable API,

whereas _getFirst() and _getLast() are meant to be private.

据我了解,方法是私有(private)的还是公共(public)的,都是由它的编写方式定义的。例如,如果我们谈论构造函数,那么“this.getFirst() = function(){ ... }”将是一个公共(public)方法,而“var getFirst=function(){...}”将是私有(private)的。

书中的示例不是构造函数。我确实相信人们不能简单地使用下划线将方法设为公共(public)或私有(private)。那么,我们如何在像上面例子那样声明的对象中创建私有(private)或公共(public)方法呢?

非常感谢!

最佳答案

Javascript 没有真正的私有(private)变量/方法。模式(下划线)只是编码约定。请参阅MDN: Private properties 。上面写着

The above technique (underscoring) is simple and clearly expresses intent. However, the use of an underscore prefix is just a coding convention and is not enforced by the language: there is nothing to prevent a user from directly accessing a property that is supposed to be private.

同时,您不能在 Object Literal {...} 构造中使用 var getFirst=function(){...}

关于javascript - Private V.S. 令人困惑的例子<Javascript Patterns> 书中的公共(public)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39382170/

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