js面向对象封装

/**
 * 一、 生成实例对象的原始模式                            主要用于初始化方法
 */
var cat1 = {}; // 创建一个空对象
    cat1.name = "大毛"; // 按照原型对象的属性赋值
    cat1.color = "黄色";
var cat2 = {};
    cat2.name = "二毛";
    cat2.color = "黑色";
cat2.init=function(){         //原型对象的方法
alert('init');
}
alert(cat1.name+"   "+cat2.name);
cat2.init();

/**
 * 二、 原始模式的改进
 */
function Cat(name,color) {
    return {
      name:name,
      color:color
    }
  }
var cat1 = Cat("大毛","黄色");
var cat2 = Cat("二毛","黑色");
/**
 * 三、 构造函数模式
 */
function aCat(name,color){
    this.name=name;
    this.color=color;
  }
var acat1 = new aCat("大毛","黄色");
  var acat2 = new aCat("二毛","黑色");
  alert(acat1.name); // 大毛
  alert(acat1.color); // 黄色


/**
 * 四、构造函数模式的问题,  多余属性浪费内存
 */
function bCat(name,color){
    this.name = name;
    this.color = color;
    this.type = "猫科动物";
    this.eat = function(){alert("吃老鼠");};
  }
var bcat1 = new bCat("大毛","黄色");
  var bcat2 = new bCat ("二毛","黑色");
  alert(bcat1.type); // 猫科动物
  bcat1.eat(); // 吃老鼠


/**
 * 五、 Prototype模式, 提高内存效率                                    比较复杂的事情下使用,常用
 */
function cCat(name,color){
    this.name = name;
    this.color = color;
  }
  cCat.prototype.type = "猫科动物";
  cCat.prototype.eat = function(){alert("吃老鼠")};
var ccat1 = new cCat("大毛","黄色");
  var ccat2 = new cCat("二毛","黑色");
  alert(ccat1.type); // 猫科动物
  ccat1.eat(); // 吃老鼠

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值