第二章 对象高级

一、对象创建模式

1.Object构造函数

 缺点:  
/* 1. 组织形式不好 2. 没有类型 3. 内存开销大 4. 代码冗余 */ var obj = new Object(); obj.age=18; obj.name="zyy"; obj.say=function () { console.log("城市套路深 我要回农村 农村路更滑 人心更复杂") } var obj2 = new Object(); obj2.age=19; obj2.name="zyy"; obj2.say=function () { console.log("-----") }

 2.字面量

缺点:

/*
  2. 没有类型
  3. 内存开销大
  4. 代码冗余
*/

改善:

// 1. 组织形式比较友好

 
var obj ={ name:"zyy", age:18, say:function () { console.log("----") } } var obj2 ={ name:"zyy2", age:38, say:function () { console.log("*****") } }

 3.工厂模式

缺点: 
/* 2. 没有类型 3. 内存开销大 */ 改善: // 1. 组织形式比较友好 // 4. 代码不冗余 function createObj(name,age,msg) { return { name:name, age:age, say:function (msg) { console.log(msg) } } } var obj = createObj("damu",18,"胡话"); var obj2 = createObj("zyy",48,"鬼话"); console.log(obj,obj2)

 4.自定义构造函数

缺点:
/* 3. 内存开销大 */ 改善: // 1. 组织形式比较友好 // 4. 代码不冗余 // 2. 拥有类型 function Person(name,age) { // var food; this.name =name; this.age =age; this.eat=function (food) { // var food; console.log(food) } } var damu = new Person("达姆",18); damu.eat("核桃"); var fyz = new Person("张艳英",48); fyz.eat("大嘴巴子"); // console.log(damu instanceof Person,fyz);

 5.自定义构造函数+原型链

 改善:   
//
1. 组织形式比较友好 // 4. 代码不冗余 // 2. 拥有类型 // 3. 内存开销相对减少 Person.prototype.eat=function (food) { console.log(this.name+"吃"+food) } function Person(name,age,food) { this.name =name; this.age =age; } var damu = new Person("达姆",18); damu.eat("核桃"); var fyz = new Person("张艳英",48); fyz.eat("大嘴巴子");

猜你喜欢

转载自www.cnblogs.com/fxiong/p/10158982.html
今日推荐