对象:在JavaScript中,对象是拥有属性和方法的数据。
JavaScript自定义对象方式有以下7种:直接创建方式、对象初始化器方式、构造函数方法、prototype原型方式、混合的构造函数/原型方式、动态原型方式和工厂模式,这里为大家讲解常用的5种:
对象初始化器方式:
标签中代码示例如下
var student={
name:"Tom",
doHomework:function(){
console.log(this.name+"正在做作业");
},
study:function(age){
console.log(this.name+"正在学习"+age);
}
}
console.log(student.name);
student.doHomework();
student.study(12)
直接创建
var student = new Object();
student.name = "Lucy";
student.study=function(){
console.log(this.name + "正在学习")
}
student.study();
构造方法式
function Student(name){
this.name=name;
this.study=function(){
console.log(this.name+"zzxx");
}
}
原型式(对象写死了)
function Student(){}
Student.prototype.name="Tim";
Student.prototype.study=function(){
console.log(this.name+"zzxx");
}
var student=new Student("Tim");
student.study();
混合式(用构造方法给属性赋值,用原型式绑定方法)
function Student(name){
this.name=name;
}
Student.prototype.study=function(){
console.log(this.name+"zzxx");
}
var student=new Student("Tim");
student.study();