JavaScript基础(十二)面向对象、ajax

面向对象

面向对象编程

面向对象编程(OOP)的特点:
	抽象:抓住核心问题
	封装:只能通过对象去执行方法
	继承:从已有的对象上继承新的对象
	多态:多个对象的不同形态(电脑USB口,接入不同的设备有不同的表现形式)
对象的组成:
	属性
	方法
// 例如
var arr = new Array(); // 系统对象
// 工厂模式 封装
function person(name){
	// 原料
	var obj = new Object();
	// 加工
	obj.name = name;
	obj.sayHello = function(){
		alert('Hello ' + this.name);
	}
	// 出厂
	return obj;
}
// var p1 = person('张三');
var p1 = new person('张三');
// var p2 = person('李四');
var p2 = new person('李四');
p1.showName();
p2.showName();

new、prototype

用new调用一个函数的时候
	这个函数创造的对象就是this
	并且默认返回的就是该this对象(隐式返回)
原型 prototype
	作用:去改写对象下面的方法或者属性为了让公用的方法或者属性在内存只“中存在一份”
		prototype只能给构造函数使用

举例

function Person(name){
	this.name = name;
	this.sayHello = function(){
		alert('Hello ' + this.name);
	}
}
var p = new Person('Lilei');
// p.sayHello();

Person.prototype.run = function(){
	alert( this.name + ' runnig!!!!' );
}
p.run(); // Lilei runnig!!!!

var p1 = new Person('Hanmeimei');
alert(p.run === p1.run); // true 内存只中存在一份,地址相同的
alert(p.sayHello === p1.sayHello); // false

案例-面向对象编程实现banner图

面向对象的写法
//构造函数
function 函数名(){
	this.属性 = ;
};
函数名.prototype.方法 = function(){
	
};
var obj = new 函数名();
obj.方法();
*{padding:0px;margin:0px;}
#box{width:500px;height:350px;margin:100px auto;position:relative;overflow: hidden;}
#list{width:1000%;height:350px;position:relative;}
#list li{list-style: none;width:500px;height:350px;float: left;}	
#list img{width:500px;height:350px;position:absolute;}
#tab ul{width:120px;height:18px;position:absolute;bottom:10px;left:50%;margin-left:-60px;}
#tab ul li{width:14px;height:14px;list-style:none;border-radius:50%;margin:4px;float:left;cursor:pointer;text-align:center;line-height:14px;background:gray;}
#tab ul li.on{background:#f60;}
<div id="box">
	<ul id="list">
		<li><img src="img/1.jpg"></li>
		<li><img src="img/2.jpg"></li>
		<li><img src="img/3.jpg"></li>
		<li><img src="img/4.jpg"></li>
		<li><img src="img/5.jpg"></li>
	</ul>
	<div id="tab">
		<ul><li class="on"></li><li></li><li></li><li></li><li></li></ul>
	</div>
</div>
window.onload = function(){
	var banner1 = new Banner();
	banner1.init();
};
//构造函数
function Banner(){
	this.imgs = document.getElementById('list').getElementsByTagName('img');
	this.lis = document.getElementById('tab').getElementsByTagName('li');
};
Banner.prototype.init = function(){
	var _this = this; // _this == this == banner1
	for(var i=0; i<this.lis.length; i++){
		this.lis[i].index = i;
		// this.oLi[i].onclick = this.toggle;
		this.lis[i].onclick = function(){
			_this.toggle(this);
		};
	}
};
Banner.prototype.toggle = function(obj){
	for(var i=0; i<this.lis.length; i++){
		this.lis[i].className = '';
		this.imgs[i].parentNode.style.display = 'none';
	}
	this.lis[obj.index].className = 'on';
	this.imgs[obj.index].parentNode.style.display = 'block';
};

包装对象

回顾一下

// 构造函数
function Person(name, age){
	this.name = name;
	this.age = age;
}
Person.prototype.showName = function(){
	alert(this.name);
	return this; // 实现链式调用
}
Person.prototype.showAge = function(){
	alert(this.age);
	return this;
}
var p = new Person('张三', 20);
// p.showName();
// 链式调用
p.showName().showAge(); // 张三 20
包装对象
	所有的基本类型都有自己对应的包装对象
	String Number Boolean
当基本类型在执行方法的时候,会先找到对应的包装对象,然后包装对象再去找对应的方法,最后执行完毕包装对象消失

例如

// Array的包装
var arr = [1, 2, 3];
// arr.push(4, 5, 6);
// alert(arr); // 1,2,3,4,5,6
// 原理
Array.prototype.push = function(){
	for(var i=0; i<arguments.length; i++){
		this[this.length] = arguments[i];
	}
}
arr.push(4, 5, 6);
alert(arr);

再例如

var str = 'abc';
// alert(str.charAt(1)); // b
// Q:基本类型为什么会有这些方法
// 原理
var str = new String('abc');
// String.prototype.charAt = function(){
// }
alert(str.charAt(1));
str.number = 10;
alert(str.number); // undefined 这是为什么? ==> 包装对象不一样
在执行“str.number = 10;”这一句时,首先是去找str对应的包装对象(String)new String(),并为该对象添加一个属性number值为10
当再执行“alert(str.number)”时,又会去找str对应的包装对象(String)new String()
这里两次new的对象是不一样的,所以结果是undefined

Ajax

Ajax:异步数据请求

// IE6 ActiveXObject
// var xhr = new XMLHttpRequest();
// 兼容写法
var xhr;
if(window.XMLHttpRequest){
	xhr = new XMLHttpRequest();
}else{
	xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
/*
	一参:请求方式  GET 或 POST
	二参:请求地址url
	三参:true==>异步  false==>同步
*/
xhr.open('get', '1.txt', true); // 同域下请求
// xhr.open('get', 'http://www.yw.nodejs-test.com:88/ajax-test/1.txt', true);
// Failed to load http://www.yw.nodejs-test.com:88/ajax-test/1.txt: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.yw.nodejs.com:88' is therefore not allowed access.
xhr.send();
xhr.onreadystatechange = function(){
	/*
		0:请求未初始化,还没有调用open的时候
		1:服务器连接已建立,还没发送,还没调用send的时候
		2:请求已接收
		3:请求处理中
		4:请求已完成,且响应已就绪
	*/
	if(xhr.readyState == 4 && xhr.status == 200){
		alert(xhr.responseText);
	}
}

简单封装

function ajax(method, url, asyn, callback){
	var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
	xhr.open(method, url, asyn);
	xhr.send();
	xhr.onreadystatechange = function(){
		if(xhr.readyState==4 && xhr.status==200){
			if(callback){
				// var response = eval("("+xhr.responseText+")");
				var response = JSON.parse(xhr.responseText);
				callback(response);
			}
		}
	}
}
// 调用
ajax('get', '1.json', true, function(response){
	console.log(response);
})

封装

function ajax(json){
	var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
	var method = json.method || 'GET';
	var url = json.url;
	var asyn = json.asyn || true;
	var data = json.data;
	var success = json.success;
	if(method.toUpperCase()=='GET' && data){
		url += '?' + data + '&_' + new Date().getTime();
	}
	xhr.open(method, url, asyn);
	// 设置请求头
	xhr.setRequestHeader('Content-Type', 'application/x-www-from-urlencoded');
	if(method.toUpperCase()=='POST' && data){
		xhr.send(data);
	}else{
		xhr.send();
	}
	xhr.onreadystatechange = function(){
		if(xhr.readyState==4 && xhr.status==200){
			if(typeof success == 'function'){
				success(JSON.parse(xhr.responseText));
			}
		}
	}
}
ajax({
	method: 'POST',
	url: '1.json',
	data: 'user=yw&age=28',
	success: function(response){
		console.log(response);
	}
})

jsonp

可以处理跨域

#box{width: 500px;margin: 100px auto;}
#txt{width: 500px;height: 30px;font-family: 'Microsoft yahei';text-indent: 1em;font-size: 14px;outline: none;}
#txt:focus{border: 1px solid #4791ff;padding: 1px;}
#list{border: 1px solid #ddd;width: 502px;display: none;}
#list li{list-style: none;width: 487px;line-height: 30px;padding-left: 15px;}
#list li:hover{cursor: pointer;background: #ddd}
#list li a{text-decoration: none;color:#333;display: inline-block;width: 100%;height: 100%;}
<div id="box">
	<input type="text" id="txt">
	<ul id="list"></ul>
</div>
<!-- 
	https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=1&cb=jsonp
	jsonp({q:"1",p:false,s:["163","12306","1688阿里巴巴批发网","126","163邮箱登录","139邮箱登陆","1688","126邮箱登录","12月13日 国家公祭日","12306铁路客户服务中心"]});
	 -->
	<!-- <script type="text/javascript" src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=1&cb=jsonp"></script> -->

案例

window.onload = function(){
	var oBox = document.getElementById('box');
	var oTxt = document.getElementById('txt');
	oTxt.onkeyup = function(e){
		var val = this.value;
		var script = document.createElement('script');
		script.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+val+'&cb=jsonp';
		document.body.appendChild(script);
		document.body.removeChild(script);
	}
}
var oList = document.getElementById('list');
function jsonp(response){
	var data = response.s;
	var len = data.length;
	if(len && len>0){
		var html = '';
		for(var i=0; i<data.length; i++){
			html += '<li><a href="https://www.baidu.com/s?wd='+data[i]+'" target="_blank">'+data[i]+'</a></li>';
		}
		oList.innerHTML = html;
		oList.style.display = 'block';
	}
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yangwei234/article/details/85019355