js面向对象 阮一峰

一:封装

一:生成实例对象的原始模型
原型对象
var Cat = { //函数子面量
name: '',
color:''
}

生成实例对象

var cat1 = {};
cat1.name = "大毛"
cat1.color = "黄色";
var cat2 = {};
cat2.name = "二毛"
cat2.color = "黄色"

二:原始模型的改进

写一个函数

function Cat(name,color) {
return {
name:name,
color:color
 }
}

生成实例对象

var cat1 = Cat("大毛""黄色");
var cat2 = Cat("二毛""黄色");

三,构造函数模式

function Cat(name,color){
this.name = name;
this.color = color;
}

生成实例对象

var cat1 =new  Cat("大毛""黄色");
var cat2 =new  Cat("二毛""黄色");

四,prototype模式
将要调用时不变的属性,定义在prototype对象上

function Cat(name,color){
this.name = name;
this.color = color;
}
Cat.prototype.type = "猫科动物";
Cat.prototype.eat = "老鼠";

生成实例

var cat1 =new  Cat("大毛""黄色");
var cat2 =new  Cat("二毛""黄色");
alert(cat1.type);
alert(cat1.eat);

二,继承

一,构造函数绑定
使用call(),apply()方法,将父对象的构造函数绑定在子对象上

function Animal() {
this.species = "动物";
}
让猫继承动物:
function Cat(name,color){
Animal.apply(this,arguments);
this.name = name;
this.color = color;
}

调用
var cat1 = new Cat("大毛""黄色");
alert(cat1.species);//动物

二,prototype模式

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛""黄色");
alert(cat1.species);//动物

三,直接继承prototype
将不变的属性直接写入prototype对象

function Animal(){}
Animal.prototype.species = "动物";

调用,省内存

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛""黄色");
alert(cat1.species);//动物

四,使用空对象作为中介

var F = function(){};
F.prototyoe = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;

封装为函数

function extend(Child,Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
//子对象上打开通道可直接调用父对象,备用
Child.uber = Parent.prototype;
}

五,拷贝继承

将不变的属性直接写入prototype对象

function Animal(){}
Animal.prototype.species = "动物";

属性拷贝

function extend2(Child,Parent){
var p = Parent.prototype;
var c= Child.prototype;
for(var i in p) {
c[i] = p[i];
 }
 c.uber = p;
}

调用

extend2(Cat,Animal);
var cat1 = new Cat("大毛""黄色");
alert(cat1.species);//动物

三,非构造函数的继承

var Chinese = {
nation :'中国'
}


var Doctor = {
career: '医生'
}

让医生去继承中国人
一,object()方法

function object(o) {
function F() {}
F.prototype = o;
return new F();
}

调用

var Doctor = object(Chinese);
Doctor.career = '医生';
alert(Doctor.nation);//中国

二,浅拷贝

function extendCopy(p) {
var c = {};
for(var i in p) {
c[i] = p[i];
}
c.urber = p;
return c;
}

调用

var Doctor = extendCopy(Chinese);
Doctor.career = '医生'
alert(Doctor.nation);//中国

存在的问题:不是真正的拷贝,子对象获得的只是一个内存地址,存在父对象被篡改的可能。

三,深拷贝
递归调用浅拷贝

function deepCopy(p,c) {
var c = c || {};
for(var in p) {
if (typeof p[i] === 'object') {
   c[i] = (p[i].constructor) === Array)?[]:{};
   deepCopy(p[i],c[i]);
  } else {
   c[i] = p[i];
  }
 }
 return c;
}
调用
var Doctor  = deepCopy(Chinese);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值