您的位置:首页 > Web前端 > JavaScript

js 动态原型方式 实现ajax异步类

2015-04-20 10:11 369 查看
js 面向对象,挺好玩的,整好上次用jquery 实现瀑布流有兼容性问题,而且是在google 上,就重新用js 写了一个,这里使用了ajax ,就把ajax 单独封装起来了。

js 面向对象有几种实现方式:

1 原始方式:对象的属性可以在对象创建后动态定义

var oCar = new Object;
oCar.color = "blue";
oCar.doors = 4;
oCar.mpg = 25;
oCar.showColor = function() {
alert(this.color);
};


2 工厂方式:开发者创造了能创建并返回特定类型的对象的工厂函数(factory function)。

function createCar() {
var oTempCar = new Object;
oTempCar.color = "blue";
oTempCar.doors = 4;
oTempCar.mpg = 25;
oTempCar.showColor = function() {
alert(this.color);
};
return oTempCar;
}

var oCar1 = createCar();
var oCar2 = createCar();


3 构造函数方式:

一步选择类名,即构造函数的名字。根据惯例,这个名字的首字母大写,以使它与首字母通常是小写的变量名分开。除了这点不同,构造函数看起来很像工厂函数。

构造函数会重复生成函数,为每个对象都创建独立的函数版本。 浪费空间

function Car(sColor,iDoors,iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.showColor = function() {
alert(this.color);
};
}

var oCar1 = new Car("red",4,23);
var oCar2 = new Car("blue",3,25);
4 原型方式:首先用空构造函数来设置类名。然后所有的属性和方法都被直接赋予 prototype 属性。

function Car() {
}

Car.prototype.color = "blue";
Car.prototype.doors = 4;
Car.prototype.mpg = 25;
Car.prototype.showColor = function() {
alert(this.color);
};

var oCar1 = new Car();
var oCar2 = new Car();


5 动态原型方式:

最为有效且节省空间的方式,下面就是一个封装

var offset = document.getElementsByName('offset')[0].value;
var length = document.getElementsByName('length')[0].value;
var post = new Post_xml_http("/Index/Show/more_photo","offset="+offset+"&length="+length);
post.create_xml_obj();
post.post();
function Post_xml_http(url,data){
//定义私有化数据,js 本质上不存在私有化
this.xml_http = null;
this.url= url;
this.data = data;

//创建xmlhttp 对象  通过动态原型方式创建对象
if(typeof Post_xml_http._initialized == "undefined"){
Post_xml_http.prototype.create_xml_obj=function(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
this.xml_http=new XMLHttpRequest();
}else{
// code for IE6, IE5
this.xml_http=new ActiveXObject("Microsoft.XMLHTTP");
}
};
Post_xml_http._initialized = true;
}

//进行post 传递数据
if(typeof Post_xml_http._post_init == "undefined"){
Post_xml_http.prototype.post =  function(){
var xmlhttp = this.xml_http;
//建立post 异步连接
xmlhttp.open("POST", this.url,true);
//设置头部信息
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(this.data);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlDoc=xmlhttp.responseText;
console.log(xmlDoc);
}
};
};
Post_xml_http._post_init = true;
}

}


效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js 动态原型 ajax 封装