日期:2014-05-16  浏览次数:20372 次

JS 面向对象学习笔记

JS 面向对象学习笔记,整理一下:

//arguments装载向函数的传参,类似数组
function add(){
	var res = 0;
	for(var i=0; i<arguments.length; i++){
		res += arguments[i];	
	}
	return res;
}

//alert(add(1,2));//3
//alert(add(1,2,3,4));//10


//call()与apply()函数的应用
var b1 = {v:'this is b1'};
var b2 = {v:'this is b2'};

function b(){
	alert(this.v);	
}

/*b();		//undifiend(this指代window)
window.b(); //undifiend(this指代window)
//call的第一个参数指代函数上下文(作用域)
b.call(b1); //this is b1(this指代b1)
b.apply(b2);//this is b2(this指代b2)*/


//类的修改【扩展】
var d = new Number(5);
d.add = function(b){
	//return this+b;	
	return this+arguments[0];
}

//alert(d.add);
//alert(d.add(6));


//如何给所有的Number的实例都加上一个add方法
//prototype属性,所有的类均具有
//给Number类的prototype属性加了一个方法,这个方法可以应用与所有的Number实例
Number.prototype.add = function(b){
	return this+b;	
}
var c = 111;
//链式语法
//alert(c.add(100).add(200).add(300));//711


//给Array类扩展一个indexOf方法
Array.prototype.indexOf = function(v){
	for(var i=0; i<this.length; i++){
		if(this[i] == v){
			return i;
		}
	}
	return -1;
}

var ii = ['11', '22'];
//alert(ii.indexOf('22')); //1


//javascript 类
function Animal(name){
	var dd = 1;//私有变量
	this.name = name; //公有变量
	this.age = 0;
	//定义私有方法
	function prMethod(){
		return dd;
	}
	//定义特权方法,可以访问私有、公有所有成员(变量dd不可销毁,闭包)
	this.sayHello = function(){
		dd++;
		var res = prMethod();
		return dd+':'+this.name+':'+this.age+':'+res;
	}
}
	
var i1 = new Animal('cat'); 
var i2 = new Animal('dog'); 

//alert(i1.sayHello()); //2:cat:0:2
//alert(i2.sayHello()); //2:dog:0:2

//此类扩展方法只能访问类的公有成员
Animal.prototype.hello = function(){
	return this.name+':'+this.age;
}

//alert(i1.hello()); //cat:0
//alert(i2.hello()); //dog:0


//继承的实现
function classA(name){
	this.name = name;
	this.showName = function(){
		return this.name;
	}
}

//类B继承类A
function classB(name){
	//继承方法一
	/*this.bMethod = classA;
	this.bMethod(name);
	delete this.bMethod;*/
	
	//执行classA函数,并将它的上下文【作用域】指向this(即为classB的实例)
	//继承方法二
	//classA.call(this, name);
	
	//继承方法三
	classA.apply(this, [name]);
}
var aa = new classA('aa');
var bb = new classB('bb');
//alert(aa.showName()); //aa
//alert(bb.showName()); //bb

//继承方法四
function classC(){
}

classC.prototype = new classB('bb1');
var cc = new classC();
cc.name = 'cc';
//alert(cc.showName()); //cc