在记录javascript方法时,我知道在名称路径中使用#
表示实例方法,如:
function Class() {}
/**
* Class#method1
*/
Class.prototype.method1 = function () {}
但是,我也看到~
和.
的使用。那些用于什么?
/**
* Class~method2
* Class.method3
*/
还有其他我应该注意的语法吗?
答案 0 :(得分:4)
您可以查看变量/方法命名约定here的详细信息。
.
用于表示类方法(也称为静态方法),而不是实例方法。这意味着在类的实例(使用new
创建的事物)上,您无法调用类方法。
示例:
Class.foo = function () {
// ...
};
var blah = new Class();
blah.foo(); // throws an error
Class.foo(); // actually calls the function
~
用于表示内部方法(也称为私有方法),它是使用function
在类的方法内定义的方法。这些类型的方法通常不能从方法外部访问,因此您很少会看到这些方法。
示例:
function Class() {
// this function is not accessible outside of the constructor
function inner() {
}
// unless we give it some other reference that is visible:
this.accessInner = inner;
}
blah = new Class();
blah.inner(); // throws an error
Class.inner(); // also throws an error
blah.accessInner(); // will actually call inner