创建对象
1.基于Object的方式创建对象
<script>
var student = new Object();
student.name = '张三';
student.age = 22;
student.javaScore = 98.5;
student.print = function () {
console.log('学生姓名:' + this.name + ",年龄:" + this.age + ",java分数:" + this.javaScore);
}
student.print();
</script>
2.对象字面量的方式创建对象
<script>
var student = {
//属性:属性值
name: '张三',
age: 23,
javaScore: 99.5,
print: function () {
console.log('学生姓名:' + this.name + ",年龄:" + this.age + ",java分数:" + this.javaScore);
}
}
console.log(student.name);
student.print();
</script>
3.工厂模式的方式创建对象
<script>
function createStudent(name, age, javaScore) {
var student = new Object();
student.name = name;
student.age = age;
student.javaScore = javaScore;
student.print = function () {
console.log('学生姓名:' + this.name + ",年龄:" + this.age + ",java分数:" + this.javaScore);
}
return student;
}
//创建对象
var stu1 = createStudent("李四", 24, 99.5);
console.log(stu1.name);
console.log(stu1.age);
console.log(stu1.javaScore);
stu1.print();
var stu2 = createStudent('王五', 19, 88.9);
stu2.print();
</script>
4.构造函数的方式创建对象
构造函数一般以大写字母开头
构造函数也是函数,只不过可以用来创建对象
<script>
function Student(name, age, javaScore) {
this.name = name;
this.age = age;
this.javaScore = javaScore;
this.print = function () {
console.log('学生姓名:' + this.name + ",年龄:" + this.age + ",java分数:" + this.javaScore);
}
}
var stu1 = new Student('如花', 18, 100);
console.log(stu1.name);
stu1.print();
</script>
原型prototype
每个函数都有一个prototype(原型)属性
这个对象的用途是包含可以由特定类型的所有实例共享的属性和方法
<script>
function Student(name, age, javaScore) {
this.name = name;
this.age = age;
this.javaScore = javaScore;
}
//在上面的构造函数中没有定义输出对象所有信息的函数,可以使用原型来进行添加
Student.prototype.print = function () {
console.log('学生姓名:' + this.name + ",年龄:" + this.age + ",java分数:" + this.javaScore);
}
var stu1 = new Student('翠花', 19, 99.9);
console.log(stu1.name);
stu1.print();
</script>