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(); // 吃老鼠

猜你喜欢

转载自blog.csdn.net/dqswuyundong/article/details/72642952