对象:在JavaScript中,对象是拥有属性和方法的数据。
JavaScript自定义对象方式有以下7种:
直接创建方式、对象初始化器方式、构造函数方法、prototype原型方式、混合的构造函数/原型方式、动态原型方式和工厂模式
这里举例5种:
1.直接创建方式
var student = new Object();
student.name = "刘清";
student.dohomework = function() {
console.log(this.name + "正在认真写作业");
}
student.dohomework();
student.name = "xiaotian";
student.dohomework();
2.对象初始化器方式
var student = {
name: "璐璐",
age: 20,
doshopping: function() {
console.log(this.name + "正在购物....");
}
};
student.doshopping();
3.构造函数方法
function Student(name) {
this.name = name;
this.doshopping = function() {
console.log(this.name + "正在购物....");
};
}
var student = new Student("小饼干");
student.doshopping();
4.prototype原型方式
function Student() {
}
Student.prototype.name = "林没听";
Student.prototype.doshopping = function() {
console.log(this.name + "正在购物....");
};
var student = new Student();
student.doshopping();
5.混合的构造函数/原型方式
function Student(name) {
this.name = name;
}
Student.prototype.doshopping=function(){
console.log(this.name + "正在购物....");
};
var student = new Student("李青贵");
student.doshopping();