创建对象的几种方法
方法一:new Object()
var stu = new Object();
stu.name = 'xiaolin';
alert(stu.name); //xiaolin
方法二:{}
var stu = {}
stu.name = 'xiaolin';
alert(stu.name); //xiaolin
var student = {name: 'xiaolin', sex: '男'};
alert(student.name); //xiaolin
方法三:function xx()
function student(name, sex) {
this.name = name;
this.sex = sex;
}
var stu1 = new student('xiaolin', '男');
alert(stu1.name); //xiaolin
var stu2 = new student('xiaohong', '女');
alert(stu2.name); //xiaohong
为对象中添加方法
方法一:
var stu = {};
stu.study = function() {
alert('learning');
}
stu.study(); //learning
方法二:
function student(name, sex) {
this.name = name;
this.sex = sex;
this.study = function() {
alert(this.name);
}
}
var stu1 = new student('xiaolin', '男');
stu1.study(); //xiaolin
var stu2 = new student('xiaohong', '女');
stu2.study(); //xiaohong