我需要一个javascript的学生班,其中包括2个数据成员名称和年龄,以及2个方法get_record()和set_record(名称,年龄)。我如何在javascript中创建并创建该类的多个对象。
答案 0 :(得分:4)
var Student = function(age, name){
this.age = age;
this.name = name;
this.get_age = function(){
return this.age;
}
this.get_name = function(){
return this.name;
}
this.set_age = function(age){
this.age = age;
}
this.set_name = function(name){
this.name = name;
}
}
var student = new Student(20,"XYZ");
答案 1 :(得分:1)
您可以使用基于JavaScript的新语言对类进行建模。 Dart和TypeScript可能是这方面最受欢迎的。
此示例基于TypeScript类的JavaScript输出。
var Student = (function() {
function Student(name, age) {
this.name = name;
this.age = age;
}
Student.prototype.get_record = function() {
return "Name: " + this.name + "\nAge: " + this.age;
}
Student.prototype.set_record = function(name, age) {
this.name = name;
this.age = age;
}
return Student;
})();
// Usage
var a = new Student("John", 23);
var b = new Student("Joe", 12);
var c = new Student("Joan", 44);
答案 2 :(得分:0)
function student (age,name) {
this.name = name;
this.age = age;
this.get_record = function() {
return "name:"+this.name+" , age:"+this.age;
}
this.set_record = function(_name,_age) {
this.name=_name;
this.age=_age;
}
}
答案 3 :(得分:0)
您可以使用'构造函数'。
function Student() {
this.get_record = function(){ return this.name; };
this.set_record = function(name, age) {
this.name = name;
this.age = age;
};
return this;
}
var student1 = new Student();
var student2 = new Student();
student1.set_record('Mike', 30);
student2.set_record('Jane', 30);
student1.get_record();
student2.get_record();
通过原型构建更复杂的类结构