我通常使用这种模式,我没有看到很多。 我这样做是为了避免必须以任何特殊方式订购我的方法。如果一切都是公开的,那么通常必须确保所调用的方法在方法调用之前声明
var person = new Person("Mo", "Yo");
person.getFullname();
person.getFirstname();
person.getLastname();
function Person(firstname, lastname) {
var firstname, lastname;
(function constructor(){
setFirstname(firstname);
setLastname(lastname)
})();
this.getFullname = getFullname; // Makes getFullName() public
function getFullname() {
// Will allow you to order method in whatever order you want.
// If we where to have it as just this.getFullname = function() {...} and same for firstname
// as it is normally done, then this.getFirstname would have to be placed before this method.
// A common pain in the ass, that you cannot order methods as you want!
return getFirstname() + ", " + getLastname();
}
this.getFirstname = getFirstname;
function getFirstname() {
return firstname;
}
function setFirstname(name){
firstname = name;
}
this.getLastname = getLastname;
function getLastname() {
return lastname;
}
function setLastname(name) {
lastname = name;
}
}
对于您的私有函数,我更喜欢'function pri(){blah; }而不是使用'var'声明。 – Pointy
“私人”概念实际上与其他语言不一样。尝试将C++,Java,C#等继承的语义映射到JavaScript提供的内容基本上是徒劳的。他们根本不同。 – Pointy