JS 创建对象的几种方式
- new Object()构造函数
var student1 = new Object();
student.name = "zs";
student.id = 123;
student.message = function(){
console.log("name:" + name + "id:" + id);
}
//调用方法
student1.message();
- 对象字面量{}
var student2 = {
name: "zs",
id: 123,
message: function(){
console.log("name:" + name + "id:" + id);
}
}
student2.message();
- 工厂函数
function createStudent(name,id){
var student = new Object();
student.name = name;
student.id = id;
student.message = function(){
console.log("name:" + this.name + "id:" + this.id);
}
return student;
}
//字面量写法
function createStudent(name,id){
return {
name : name;
id : id;
message : function(){
console.log("name:" + this.name + "id:" + this.id);
}
};
}
//生成真正的对象
var student3 = createStudent("zs",456);
var student4 = createStudent("zw",123);
student3.message();
-
自定义构造函数
-
构造函数是根据具体的事物抽象出来的抽象模板
-
实例对象是根据抽象的构造函数模板得到的具体实例对象
-
与工厂函数不同的是,构造函数的命名首字母大写,构造函数内部,不用构造一个空对象再赋值给变量里,直接将属性添加给this关键字,没有return语句。
-
function Student(name,id){
this.name = name;
this.id = id;
this.message = function(){
console.log(this.name + "," + this.id);
};
}
//生成对象实例
var student5 = new Student("ls",789);
//调用方法
student5.message();