对象:无序的属性的集合,key 字符串(不重复),value 任何数据类型
表现方式:
{"key":value,"key2":value2,"key3":function () {} }
‘:’ 代表映射
‘=’ 代表赋值
第一种:new Object()
var x = "age";
var obj = new Object();
obj.name = "show";
obj.x = 18; //字符串
obj[x] = 40; //变量
console.log(obj);
第二种:字面量
var x = "hooby";
var obj = {"name":"show","age":18};
obj.sex = "man";
obj[x] = "dance";
obj.say = function () {
}
console.log(obj);
第三种:工厂函数
写法:
1、创建函数
2、传入参数
3、函数内创建对象
4、return 对象
调用:函数名(参数)
优点:返回新对象,互不影响
缺点:代码重复(相同方法)、没有从属(不能知道对象从哪里来)- -> instanceof 只能判断是对象,不能判断属于谁
function students(name, age){
var obj = {
"name":name,
"age":age,
"say":function () {}
}
return obj;
}
var obj1 = students("show",18);
console.log(obj1);
console.log(obj1 instanceof Object); //true
console.log(obj1 instanceof students); //false
第四种:构造函数
写法:
1、创建函数
2、传入参数
3、this.属性名 = 值
调用:var obj = new 构造函数(参数)
优点:有从属
缺点:代码重复(相同方法)
共识:构造函数的首字母大写
function Students (name, age) {
this.name = name;
this.age = age;
this.say = function () {}
}
var obj1 = new Students("show",18);
console.log(obj1);
console.log(obj1 instanceof Object); //true
console.log(obj1 instanceof Students); //true
第五种:原型对象
原型:每个函数中都有一个prototype属性,属性的值是对象,这个对象叫原型对象。
优点:公共/相同的属性、方法不重复,有从属关系
缺点:原型上的属性不可单独改变
function Fn () {
}
Fn.prototype.name = "show";
Fn.prototype.age= 18;
Fn.prototype.say = function () {};
var obj1 = new Fn ();
console.log(obj1);
第六种:组合模式
组合模式就是构造函数模式+原型模式
有从属关系且不重复
属性定义在构造函数内,方法定义在构造函数的原型对象上。
function Fn(name, age){
this.name = name;
this.age = age;
}
Fn.prototype.say = function () {
console.log("啦啦啦");
}
var obj1 = new Fn("show",18);
var obj2 = new Fn("li",20);
console.log(obj1);
console.log(obj2);
obj1.say();
obj2.say();