1.字面量创建(JSON格式创建)创建了一个名字为obj1的空对象
var obj1 = {};
可以通过.语法或者[]语法为对象添加属性或方法.
obj1.name = ‘小白‘;
obj1.age = ‘3‘;
obj1.sex = ‘男‘;
obj1.idCard = ‘1234567898974565123213‘
obj1.height = ‘180cm‘;
obj1.weight = ‘60kg‘;
obj1.run =function(){
console.log(‘随风奔跑‘)
}
obj1.eat =function(){
console.log(‘朱若‘)
}
var str = ‘我的名字叫‘+obj1.name+‘,我今年‘+obj1.age+‘岁了.‘;
console.log(str);
obj1.eat();
2.通过系统构造函数创建
var obj3 = new Object();//创建空对象
3.工厂模式创建对象(创建同学对象的工厂)
function createStudent (id,name,sex,age){
创建空对象
var obj = new Object;
添加属性
obj.id =id;
obj.name =name;
obj.sex =sex;
obj.age = age;
返回对象
return obj;
}
var student1 = new createStudent(‘01‘,‘张‘,‘男‘,‘15‘);
var student2 = new createStudent(‘02‘,‘可‘,‘女‘,‘18‘);
console.log(student1,student2);
ript>
//通过自定义构造函数创建
function People(name,age){
this.name = name;
this.age =age;
this.say =function(){
console.log(‘我是‘+this.name+‘,我今年‘+this.age+‘岁.‘)
}
}
4.通过new和构造函数创建对象实例
var p1=new People(‘小红‘,‘20‘);
console.log(p1)
p1.say();
原文地址:https://www.cnblogs.com/baobao524/p/10224384.html