第五章、原型
5.1 原型属性
5.1.4 利用自身属性重写原型属性
如果在一个对象自身属性中没有找到指定的属性,就可以去原型链中查找相关属性。但是如果遇上对象自身属性与原型链属性同名时,那么对象自身属性的优先级高于原型链属性。
functionGadget(name,color){
this.name = name;
this.color = color;
this.method =function(){
return 1;
}
}
Gadget.prototype.price = 10;
Gadget.prototype.rating = 3;
var newtoy = new Gadget('webcam','back');
for(var prop in newtoy){
console.log(prop + '=' + newtoy[prop]);
}
//name=webcam
//color=back
//method=function (){return 1;}
//price=10
//rating=3
hasOwnProperty()方法用于区分对象自身属性(返回true)与原型属性(返回false)
newtoy.hasOwnProperty('name'); //true
newtoy.hasOwnProperty('price'); //false
propertyIsEnumerable()方法对所有非内建对象属性返回true,表示可通过for-in枚举;
newtoy.propertyIsEnumerable('name'); //true
isPrototypeOf()方法会告诉我们当前对象是否是另一个对象的原型
var monkey = {
hair:true,
feeds:'bananas',
breathes:'air'
};
functionHuman(name){
this.name = name;
}
Human.prototype = monkey;
var jesse = new Human('Jesse');
monkey.isPrototypeOf(jesse); //true
5.2 扩展内建对象
为Array对象添加inArray()方法,用于查询数组中是否存在某个特定的值
if(!Array.prototype.inArray){ //如果想通过原型为某个对象添加新属性,请务必检查该属性是否已存在
Array.prototype.inArray = function (needle){
for(var i = 0;i < this.length; i++){
if(this[i] == needle){
return true;
}
}
return false;
}
}
var a = ['a','b','c'];
a.inArray('d'); //false
为String对象添加reverse()方法,用于反向输出该字符串
if(!String.prototype.reverse){ //如果想通过原型为某个对象添加新属性,请务必检查该属性是否已存在
String.prototype.reverse = function(){
return Array.prototype.reverse.apply(this.split('')).join('');
}
}
"Jesse".reverse(); //"esseJ"
//首先利用this.split('')将目标字符串转为数组,并作为apply()的第二个参数,第一个参数不传值时默认为全局对象
//再调用数组的reverse()方法生成反向数组
//最后通过join()方法将数组转化为字符串
5.2.2 原型陷阱
- 当我们对原型对象完全替换时,可能会触发异常
- prototype.constructor属性不可靠
解决方法:当我们重写某对象的prototype时,必须重置相应的constructor属性
5.4 练习题
var shape = {
type:"triangle",
getType:function(){
return this.type;
}
}
functionTriangle(a,b,c){
this.a = a;
this.b = b;
this.c = c;
}
Triangle.prototype = shape;
//当我们重写某对象的prototype时,必须重置相应的constructor属性
Triangle.prototype.constructor = Triangle;
Triangle.prototype.getPerimeter = function(){
return this.a + this.b + this.c;
}
var t = new Triangle(1,2,3);
for(var prop in t){
if(t.hasOwnProperty(prop)){
console.log(prop + '=' + t[prop]);
}
}
t.constructor; //Trianle(a,b,c)
shape.isPrototypeOf(t); //true
t.getPerimeter(); //6
t.getType(); //"triangle"
第六章、继承
6.1.1 原型链示例
functionShape(){
this.name = 'shape';
this.toString = function(){return this.name;};
}
functionTwoDShape(){
this.name = '2D shape';
}
functionTriangle(side,height){
this.name = 'Triangle';
this.side = side;
this.height = height;
this.getArea = function(){
return this.side*this.height/2;
}
}
TwoDShape.prototype = new Shape();
Triangle.prototype = new TwoDShape();
//我们用构造器Shape()另建了一个新的实体,然后用它去覆盖该对象的原型
//这确保了在继承实现之后,我们对Shape()所进行的任何修改、重写、删除都不会对TwoShape()产生影响
TwoDShape.prototype.constructor = TwoDShape;
Triangle.prototype.constructor = Triangle;
var my = new Triangle(5,10);
my.getArea();//25
my.toString(); // Triangle
6.1.2 将共享属性迁移到原型中
functionShape(){};
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){return this.name;};
functionTwoDShape(){};
TwoDShape.prototype = new Shape();
TwoDShape.prototype.constructor = TwoDShape;
//我们需要在对原型对象进行扩展之前,先完成相关继承关系的构建
TwoDShape.prototype.name = '2D shape';
functionTriangle(side,height){
this.side = side;
this.height = height;
}
Triangle.prototype = new TwoDShape();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function(){
return this.side*this.height/2;
}
6.2 只继承于原型
functionShape(){};
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){return this.name;};
functionTwoDShape(){};
//TwoDShape.prototype = new Shape(); new Shape()会将Shape的属性设定为对象自身属性,这样的代码是不可重用的
TwoDShape.prototype = Shape.prototype;
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.prototype.name = '2D shape';
functionTriangle(side,height){
this.side = side;
this.height = height;
}
Triangle.prototype = TwoDShape.prototype;
//这样固然可以提高效率,但是子对象和父对象都指向同一对象,一旦对原型属性进行修改,继承的对象相关属性也随之改变
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function(){
return this.side*this.height/2;
}
var s = new Shape();
s.name;//"Triangle"
6.3 uber--子对象访问父对象的方式
在构建继承关系的过程中引入一个uber属性,并令其指向其父级原型对象
6.8 深拷贝
当对象类型的属性拷贝时,实际上拷贝的只是该对象在内存中的位置指针,这一过程就是浅拷贝
//浅拷贝
functionextendCopy(p){
var c = {};
for(var i in p){
c[i] = p[i];
}
c.uber = p;
return c;
}
//深拷贝
functiondeepCopy(p,c){
var c = c || {};
for(var i in p){
if(typeof p[i] === 'object'){
c[i] = (p[i].constructor == Array) ? [] : {};
deepCopy(p[i],c[i]); //在遇到一个对象引用型的属性时,需要再次调用深拷贝
}else{
c[i] = p[i];
}
}
return c;
}
var parent = {
numbers:[1,2,3],
letters:['a','b','c'],
obj:{prop:1},
bool:true
};
var mydeep = deepCopy(parent);
var myshallow = extendCopy(parent);
mydeep.numbers.push(4,5,6); //6
mydeep.numbers; //[1, 2, 3, 4, 5, 6]
parent.numbers; //[1, 2, 3]
myshallow.numbers.push(10); //4
myshallow.numbers; //[1, 2, 3, 10]
parent.numbers; //[1, 2, 3, 10]
mydeep.numbers; //[1, 2, 3, 4, 5, 6]
6.9 object
基于在对象之间直接构建继承关系的理念,可以用object()来接收父对象,并返回一个以该父对象为原型的
新对象。
functionobject(p){
functionF(){};
F.prototype = p;
return new F();
}
6.12 寄生式继承
var twoD = {
name:'2d shape',
dimensions:2
}
functiontriangle(s,h){
var that = object(twoD);//把twoD对象全属性拷贝进that对象
that.name = 'Triangle';
that.getArea = function(){return this.side * this.height / 2};
that.side = s;
that.height = h;
return that;
}
6.14 本章小结
实现继承的方法大致上分为两类:
- 基于构造器工作模式
- 基于对象工作模式



6.15 案例学习:图形绘制
未完成
第七章、浏览器环境
7.3 BOM
7.3.1 Window对象
window.open('新URL','新窗口名','以逗号分割的功能性列表')
window.close();
window.moveTo(x,y);
window.moveBy(x,y);
window.resizeTo(x,y);
window.resizeBy(x,y);
window.alert();
window.prompt(); //点击确认返回相应文本,点击取消返回null
window.confirm();//点击确认返回true,点击取消返回false
window.setTimeout();//指定多长时间后执行代码
window.setInterval();//指定每隔多长时间执行代码
7.3.2 navigation对象
navigation.userAgent是一个用户浏览器识别的长字符串,但不要过分依赖这种用户代理字符串,
浏览器能力检测是更好地选择
- 这种字符串很难追踪到所有的浏览器以及其各种版本
- 这种字符串可以被修改
7.3.3 location对象
localtion对象的完整��性:
- href
- hash
- host
- hostname
- port
- protocol
- search
location对象的方法:
- reload()重载某页面
- assign()打开新URL,并在历史记录中生成新纪录
- replace()与assign()相同,但不会生成新纪录
7.3.4 history对象
history.forward();history.back();
7.3.5 screen对象
screen.width();
screen.availwidth();
7.4 DOM
7.4.2 DOM节点的访问
hasChildNodes()方法用于判断一个节点是否存在子节点
hasAttributes()方法用于检查该元素中书否存在属性
document.documentElement.childNodes.length; //2
//任何节点都可以通过自身的parentNode来访问它的父节点
document.documentElement.parentNode; //<html>
document.getElementsByTagName();
document.getElementsByName();
document.getElementById();
nextSibling/previousSibling;
firstChild/lastChild
7.4.4 新建节点
createElement();
var myp = document.createElement('p');
createTextNode();//新建文本节点
appendChild();
document.body.appendChild(myp);
cloneNode(true)//true深拷贝 false浅拷贝
insertBefore(要插入的节点,参照节点);
replaceChild(要插入的节点,要替换的节点)
removeChild(要移除的节点);
7.5 事件
7.5.3 DOM的事件监听器
addEventListener('事件类型',函数指针[,false]);
removeEventListener('事件类型',函数指针[,false]);
//匿名函数所定义的监听器是不能被移除的
该方法基于某一节点对象来调用,第三个参数决定代码是否采用事件捕捉,可选的,为了适应更多的浏览器,我们一般将其设置为false,即采用事件冒泡。
7.6 XMLHttpRequest对象
//创建xhr对象
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
//设置一个能触发readystatechange事件的事件监听器,及处理响应程序
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){
console.log(xhr.responseText);
}
}
//open(请求类型,请求目标URL,是否异步请求)
xhr.open('GET','somefile.txt',true);
//发送请求
xhr.send('')
7.8 练习题
2.3
functioninclude(js){
var script = document.createElement('script');
script.src = js;
document.body.appendChild(script);
}
include('somescript.js');
3.1
var myevent = {
addListener:function(el,type,fn){
if(typeof window.addEventListener === 'function'){
myevent.addListener = function(el,type,fn){
el.addEventListener(type,fn,false);
};
}else if(typeof window.attachEvent === 'function'){ //code for IE
myevent.addListener = function(el,type,fn){
el.attachEvent('on'+type,fn);
};
}else{ // code for older browsers
myevent.addListener = function(el,type,fn){
el['on' + type] = fn;
};
}
myevent.addListener(el,type,fn);
},
removeListener : function(el,type,fn){
if(typeof window.removeEventListener === 'function'){
myevent.removeListener = function(el,type,fn){
el.removeEventEventListener(type,fn,false);
};
}else if(typeof window.detachEvent === 'function'){ //code for IE
myevent.removeListener = function(el,type,fn){
el.detachEvent('on'+type,fn);
};
}else{ // code for older browsers
myevent.removeListener = function(el,type,fn){
el['on' + type] = null;
};
}
myevent.removeListener(el,type,fn);
},
getEvent:function(event){},
getTarget:function(event){},
stopPropagation:function(event){},
preventDefault:function(event){}
}
4.1
var ajax ={
request:function(url,requestType,queryString){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
}
xhr.open(requestType,url,true);
xhr.send('');
}
}
ajax.request('some.txt','get');
第八章、编程模式与设计模式
8.1 编程模式
8.1.2 命名空间与初始化分支模式
为了减少命名冲突,最好的办法是将变量和方法定义在不同的命名空间中,这种方法的实质是只定义一个全局变量,
并将其他的方法和属性定义为该变量的属性。
var mySpace = {};
mySpace.event = {
addListener:null,
removeListener:null
……
}
if(typeof window.addEventListener === 'function'){
mySpace.event.addListener = function(el,type,fn){
el.addEventListener(type,fn,false);
};
mySpace.event.removeListener = function(el,type,fn){
el.removeEventListener(type,fn,false);
};
}else if(typeof window.attachEvent === 'function'){ //code for IE
mySpace.event.addListener = function(el,type,fn){
el.attachEvent('on'+type,fn);
};
mySpace.event.removeListener = function(el,type,fn){
el.detachEvent('on'+type,fn);
};
}else{ // code for older browsers
mySpace.event.addListener = function(el,type,fn){
el['on' + type] = fn;
};
mySpace.event.removeListener = function(el,type,fn){
el['on' + type] = null;
};
}
8.1.4 延迟定义模式
var mySpace = {};
mySpace.event = {
addListener:function(el,type,fn){
if(typeof window.addEventListener === 'function'){
mySpace.event.addListener = function(el,type,fn){
el.addEventListener(type,fn,false);
};
}else if(typeof window.attachEvent === 'function'){ //code for IE
mySpace.event.addListener = function(el,type,fn){
el.attachEvent('on'+type,fn);
};
}else{ // code for older browsers
mySpace.event.addListener = function(el,type,fn){
el['on' + type] = fn;
};
}
mySpace.event.addListener(el,type,fn);
}
};
8.1.5 配置对象
该模式适用于有很多参数的函数或方法
用单个对象来替代多个参数有以下几点优势:
- 不用考虑参数的顺序
- 可以跳过某些参数的设置
- 函数的扩展性强
- 代码可读性好
var myapp = {};
myapp.dom = {};
myapp.dom.Button = function(text,conf){
var type = conf.type || 'submit';
var font = conf.font || 'microsoftyahei';
//……
}
//使用方法如下:
var config = {
font:'Arial,Verdana,microsoftyahei',
color:'#fff'
};
new myapp.dom.Button('lalala',config);
8.1.6 私有属性和方法
8.1.7 特权函数
8.1.8 私有函数的公有化
8.1.9 自执行函数
(function(){
// code in here
})()
//该模式特写适用于某些脚本加载时所执行的一次性初始化工作
8.1.10 链式调用
构造器返回的是新建对象的this指针,我们可以使用这些方法所返回的实例来调用其他方法
document.body.appendChild(
new mySpace.dom.Element('span')
.setText('hello')
.setStyle('color','red')
);
8.1.11 JSON
var obj = JSON.parse(xhr.responseText);
8.2 设计模式
8.2.2 单件模式
8.2.3 工厂模式
8.2.4 装饰器模式
8.2.5 观察者模式
本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-04/130053.htm
