JavaScript有很多用来很多创建对象的方法,根据不同的场景需要和自己的喜好可以采取不同的创建方式。
下面是常见的8种创建方式。
1、使用Object()构造函数创建
var objA=new Object();
objA.name='张三';
objA.gender='男';
objA.age=19;
objA.info=function(){
console.log('姓名:'+this.name+',性别:'+this.gender+',年龄:'+this.age);
}
objA.info();
2、基于对象字面量创建
var objB={
name:'张三',
gender:'男',
age:19,
info:function(){
console.log('姓名:'+this.name+',性别:'+this.gender+',年龄:'+this.age);
}
}
objB.info();
3、使用工厂模式创建
function createObj(name,age,gender){
var obj=new Object();
obj.name=name;
obj.age=age;
obj.gender=gender;
obj.info=function(){
console.log('姓名:'+this.name+',性别:'+this.gender+',年龄:'+this.age);
}
return obj;
}
var objC1=createObj('小王',11,'男');
objC1.info();
var objC2=createObj('小宋',9,'女');
objC2.info();
4、使用构造函数创建
function Student(name,age,gender){
this.name=name;
this.age=age;
this.gender=gender;
this.info=function(){
console.log('姓名:'+this.name+',性别:'+this.gender+',年龄:'+this.age);
}
}
var objD1=new Student('小王',11,'男');
objD1.info();
var objD2=new Student('小宋',9,'女');
objD2.info();
console.log(objD1 instanceof Student);
5、使用Object.create()方法创建
var stu={
name:'小李',
age:12,
gender:'男',
info:function(){
console.log('姓名:'+this.name+',性别:'+this.gender+',年龄:'+this.age);
}
}
var objE1=Object.create(stu);
objE1.name='小黄';
objE1.age=10;
objE1.gender='女';
objE1.info();
6、基于原型创建
function studentObj(){};
studentObj.prototype.name='小黑';
studentObj.prototype.age=8;
studentObj.prototype.gender='男';
studentObj.prototype.info=function(){
console.log('姓名:'+this.name+',性别:'+this.gender+',年龄:'+this.age);
}
var stuG1=new studentObj();
stuG1.name='小王';
stuG1.age=11;
stuG1.gender='男';
stuG1.info();
var stuG2=new studentObj();
stuG2.name='小宋';
stuG2.age=9;
stuG2.gender='女';
stuG2.info();
7、基于构造函数和原型想结合的方式创建
function stuObj(name,age,gender){
this.name=name;
this.age=age;
this.gender=gender;
}
stuObj.prototype.info=function(){
console.log('姓名:'+this.name+',性别:'+this.gender+',年龄:'+this.age);
}
var stuH1=new stuObj('小王',11,'男');
stuH1.info();
var stuH2=new stuObj('小宋',9,'女');
stuH2.info();
8、使用class创建(ES6的写法)
class stud{
constructor(name,age,gender) {
this.name=name;
this.age=age;
this.gender=gender;
this.info=function(){
console.log('姓名:'+this.name+',性别:'+this.gender+',年龄:'+this.age);
}
}
}
var objF1=new stud('小王',11,'男');
objF1.info();
var objF2=new stud('小宋',9,'女');
objF2.info();
console.log(objF1 instanceof stud);