JavaScript中属性和方法名称的下划线前缀 [英] Underscore prefix for property and method names in JavaScript

查看:171
本文介绍了JavaScript中属性和方法名称的下划线前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中的下划线前缀只是一个约定,例如在Python私有类方法中是什么?

Is the underscore prefix in JavaScript only a convention, like for example in Python private class methods are?

来自2.7 Python文档:

From the 2.7 Python documentation:



的私有实例变量除了从
内部访问外,Python中不存在对象。
但是,有一个约为
的约定,其次是大多数Python代码:名称
前缀为下划线(例如
_spam)应被视为非公开部分API(无论是
是函数,方法还是数据
成员)。

"Private" instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member).

这是也适用于JavaScript?

Does this also apply to JavaScript?

以此JavaScript代码为例:

Take for example this JavaScript code:

function AltTabPopup() {
    this._init();
}

AltTabPopup.prototype = {
    _init : function() {
        ...
    }
}

此外,还使用了下划线前缀变量。

Also, underscore prefixed variables are used.

    ...
    this._currentApp = 0;
    this._currentWindow = -1;
    this._thumbnailTimeoutId = 0;
    this._motionTimeoutId = 0;
    ...

仅限约定?或者下划线前缀后面是否有更多?

Only conventions? Or is there more behind the underscore prefix?

我承认我的问题非常类似于这个问题,但它没有让人更聪明地了解JavaScript中下划线前缀的重要性。

I admit my question is quite similar to this question, but it didn't make one smarter about the significance of the underscore prefix in JavaScript.

推荐答案

这只是一个惯例。 Javascript语言对以下划线字符开头的标识符没有任何特殊含义。

That's only a convention. The Javascript language does not give any special meaning to identifiers starting with underscore characters.

这就是说,对于不支持封装开箱即用。虽然没有办法阻止某人滥用你的类的实现,但至少它确实澄清了你的意图,并且首先将这些行为记录为错误

That said, it's quite a useful convention for a language that doesn't support encapsulation out of the box. Although there is no way to prevent someone from abusing your classes' implementations, at least it does clarify your intent, and documents such behavior as being wrong in the first place.

这篇关于JavaScript中属性和方法名称的下划线前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆