在JavaScript中,它更多的是約定。首先使用下劃線來定義私有屬性或方法,如_private
。有了幾個助手,你可以輕鬆地上課。我覺得這個設置很容易的,你需要的是一個輔助inherits
擴展類,而不是使用多個參數,你在一個對象props
通過,並只需撥打「超級」在繼承的類與arguments
。例如,使用一個模塊的模式:需要的一切祕密的進行
Function.prototype.inherits = function(parent) {
this.prototype = Object.create(parent.prototype);
};
var Person = (function PersonClass() {
function Person(props) {
this.name = props.name || 'unnamed';
this.age = props.age || 0;
}
Person.prototype = {
say: function() {
return 'My name is '+ this.name +'. I am '+ this.age +' years old.';
}
};
return Person;
}());
var Student = (function StudentClass(_super) {
Student.inherits(_super);
function Student(props) {
_super.apply(this, arguments);
this.grade = props.grade || 'untested';
}
Student.prototype.say = function() {
return 'My grade is '+ this.grade +'.';
};
return Student;
}(Person));
var john = new Student({
name: 'John',
age: 25,
grade: 'A+'
});
console.log(JSON.stringify(john)); //=> {"name":"John","age":25,"grade":"A+"}
console.log(john.say()); //=> "My grade is A+"
關於私有變量「問題」只是堅持約定實例的屬性和使用閉。
準確地說,在這種情況下,您的字段「private」仍然是公開的。 – 2013-03-05 06:53:27
@ Chips_100是的,但這不是要求的一部分。 – melpomene 2013-03-05 06:54:09