js面向对象封装
2017-05-23 15:49
225 查看
/**
* 一、 生成实例对象的原始模式 主要用于初始化方法
*/
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(); // 吃老鼠
* 一、 生成实例对象的原始模式 主要用于初始化方法
*/
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(); // 吃老鼠
相关文章推荐
- js面向对象二--封装
- 【原生js】js面向对象三大特征之封装笔记
- js面向对象之构造函数、封装与继承
- js面向对象之封装(构造函数)
- JS面向对象(封装,继承)
- js面向对象封装例子
- 利用JS面向对象+模块化封装集AJAX请求、基本数据校验、URL参数截取等功能于一身的通用工具模块
- js面向对象--封装
- JS面向对象封装
- js面向对象的封装
- js之面向对象----封装篇
- 韩顺平 javascript教学视频_学习笔记19_js面向对象三大特征(封装,继承,多态)
- js实现对ajax请求面向对象的封装
- 前端那些事之原生js--面向对象封装轮播图
- js面向对象-封装
- 对象(类)的封装方式(面向对象的js基本知识)
- JS-面向对象-封装
- js--面向对象--封装
- 拖拽系列二、利用JS面向对象OOP思想实现拖拽封装
- 利用JS面向对象+模块化封装集AJAX请求、基本数据校验、URL参数截取等功能于一身的通用工具模块