JavaScript creates objects
JavaScript provides some commonly used built -in objects (introduced later), but in some cases we need to customize the objects to achieve special and rich functions.
For example, we create a "Student" object and specify several attributes and methods for them:
student = new Object(); // 创建对象“student” student.name = "Tom"; // 对象属性 名字 student.age = "19"; // 对象属性 年龄 student.study =function() { // 对象方法 学习 alert("studying"); }; student.eat =function() { // 对象方法 吃 alert("eating"); };
In addition, you can also create this object:
var student = {}; student.name = "Tom"; ……
or this way :
var student = { name:"Tom"; age:"19"; …… }
However, the above method will generate a lot of repeated code when creating multiple objects, so we can also use functions to create new objects:
function student(name,age) { this.name = name; this.age = age; this.study = function() { alert("studying"); }; this.eat = function() { alert("eating"); } }
Then create an instance of the student object through new :
rreeevar student1 = new student('Tom','19'); var student2 = new student('Jack','20');