目的:
创建符合预期的对象
创建对象的方法
1. var object={};
2. var object2 = new Object();
给对象赋值的四种方法
// 1. 点赋值
object.pointMethod = "pointMethod";
console.log(object);
//2. [] 赋值法
object["bracketMethod"] = "bracketMethod";
console.log(object);
//3 defineProperty
Object.defineProperty(object ,"defineProperty", {
value :"defineProperty",
writable : true ,
enumerable : true ,
configurable : true
})
console.log(object);
//4 defineProperties
Object.defineProperties(object , {
"defineProperties1":{
value:"defineProperties1",
writable: true,
enumerable : true ,
configurable : true
},
"defineProperties2":{
value :"defineProperties2",
writable:true,
enumerable : true ,
configurable : true
}
})
console.log(object);
实例化对象
//实例化对象
function Car(model,year,miles) {
this.model = model;
this.year = year;
this.miles = miles;
this.toString = function(){
return this.model + this.year + this.model;
}
}
var civic = new Car("civic",2009,20000);
var monde = new Car("monde",2009,20000);
普通实例化对象的缺点
1.toString 是为每个使用构造器创建的新对象重新定义的。
2 继承变得困难
利用原型的构造器模式
//利用prototype
function Car2(model,year,miles) {
this.model = model;
this.year = year;
this.miles = miles;
}
Car2.prototype.tostring =function(){
return this.model + this.year + this.model;
}
var civic2 = new Car2("civic2" , 2009,20000);
// 把原来是构造器里面的方法 添加到构造器的原型中去,每个生成的都会继承这个方法。不用一直重新定义。类似把原来是妈妈的 部分给了姥姥。