我需要一个带有 2 个数据成员名称和年龄以及 2 个方法 get_record() 和 set_record(name,age) 的 javascript 学生类。我如何在 javascript 中执行此操作并创建该类的多个对象。
问问题
151 次
4 回答
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");
于 2013-06-11T08:44:34.697 回答
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);
于 2013-06-11T08:47:56.983 回答
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;
}
}
于 2013-06-11T08:43:10.293 回答
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();
更复杂的类结构是通过原型构建的
于 2013-06-11T08:46:35.737 回答