蛋疼的js 之 OOP .

来源:http://blog.csdn.net/wll525775008/article/details/17308033

  js不像别的语言,他是没有class的,但却是无处不对象的。我们可以通过很多方法模拟构建类以及继承等。

    先来捋一下js对象的创建吧:    

[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
//第1种写法  
function Circle(r) {
    this.r = r;
    var fun1 = function(){
        alert(234)
    }
} 
Circle.PI = 3.14159; 
Circle.prototype.area = function() { 
    return Circle.PI * this.r * this.r;
}
var c = new Circle(1.0);
alert(c.area()); 
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
//第2种写法
var Circle = function() { 
   var obj = new Object(); 
   obj.PI = 3.14159; 

   obj.area = function( r ) { 
       return this.PI * r * r;
   }  
   return obj; 
}  

var c = new Circle(); 
alert( c.area( 1.0 ) ); 
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. //第3种写法   
  2. var Circle = new Object();  
  3. Circle.PI = 3.14159;   
  4. Circle.Area = function( r ) {   
  5.      return this.PI * r * r;    
  6. }    
  7.   
  8. alert( Circle.Area( 1.0 ) );  
//第3种写法
var Circle = new Object();
Circle.PI = 3.14159; 
Circle.Area = function( r ) { 
     return this.PI * r * r;  
}  

alert( Circle.Area( 1.0 ) );
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. //第4种写法   
  2. var Circle={    
  3.     "PI":3.14159,   
  4.     "area":function(r){  
  5.           return this.PI * r * r;  
  6.     }    
  7. };    
  8. alert( Circle.area(1.0) );  
//第4种写法
var Circle={  
    "PI":3.14159, 
    "area":function(r){
          return this.PI * r * r;
    }  
};  
alert( Circle.area(1.0) );
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. //第5种写法     
  2. var Circle = new Function("this.PI = 3.14159;this.area = function( r ) {return r*r*this.PI;}");    
  3. alert( (new Circle()).area(1.0) );   
//第5种写法  
var Circle = new Function("this.PI = 3.14159;this.area = function( r ) {return r*r*this.PI;}");  
alert( (new Circle()).area(1.0) ); 


 

再来捋一下js的继承

  Javascript本身是从Perl语言的语法演变而来的,本质上是脚本语言,随着版本的更新逐渐加入的对面向对象的模拟。我认为Js的面向对象模拟总体上做得还是不错的,因为我们不能盲从任何一种理念,不能纯粹的为了OOP而OOP,我们需要抓住的是面向对象的好处到底是什么?为了这些优点去OOP,才是最明智的选择,所以说Js做得还不错。
  Js的继承在很多书里面细致的分了很多种类型和实现方式,大体上就是两种:对象冒充、原型方式。这两种方式各有优点和缺陷,这里我先列举出来,再从底层分析区别:

(一)对象冒充

[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function A(name){  
  2.     this.name = name;  
  3.     this.sayHello = function(){alert(this.name+” say Hello!”);};  
  4. }  
  5.   
  6. function B(name,id){  
  7.     this.temp = A;  
  8.     this.temp(name);        //相当于new A();   
  9.     delete this.temp;        //防止在以后通过temp引用覆盖超类A的属性和方法   
  10.      this.id = id;     
  11.     this.checkId = function(ID){alert(this.id==ID)};  
  12. }  
function A(name){
    this.name = name;
    this.sayHello = function(){alert(this.name+” say Hello!”);};
}

function B(name,id){
    this.temp = A;
    this.temp(name);        //相当于new A();
    delete this.temp;        //防止在以后通过temp引用覆盖超类A的属性和方法
     this.id = id;   
    this.checkId = function(ID){alert(this.id==ID)};
}
  当构造对象B的时候,调用temp相当于启动A的构造函数,注意这里的上下文环境中的this对象是B的实例,所以在执行A构造函数脚本时,所有A的变量和方法都会赋值给this所指的对象,即B的实例,这样子就达到B继承了A的属性方法的目的。之后删除临时引用temp,是防止维护B中对A的类对象(注意不是实例对象)的引用更改,因为更改temp会直接导致类A(注意不是类A的对象)结构的变化。    我们看到了,在Js版本更新的过程中,为了更方便的执行这种上下文this的切换以达到继承或者更加广义的目的,增加了call和apply函数。它们的原理是一样的,只是参数不同的版本罢了(一个可变任意参数,一个必须传入数组作为参数集合)。这里就以call为例子,解释一下用call实现的对象冒充继承。
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function Rect(width, height){  
  2.     this.width = width;  
  3.     this.height = height;  
  4.     this.area = function(){return this.width*this.height;};  
  5. }  
  6.   
  7. function myRect(width, height, name){  
  8.     Rect .call(this,width,height);  
  9.     this.name = name;  
  10.     this.show = function(){  
  11.     alert(this.name+” with area:”+this.area());  
  12.     }  
  13. }  
function Rect(width, height){
    this.width = width;
    this.height = height;
    this.area = function(){return this.width*this.height;};
}

function myRect(width, height, name){
    Rect .call(this,width,height);
    this.name = name;
    this.show = function(){
    alert(this.name+” with area:”+this.area());
    }
}

  关于Call方法,官方解释:调用一个对象的一个方法,以另一个对象替换当前对象。 
  call (thisOb,arg1, arg2…)
  这也是一种对象冒充的继承,其实在call方法调用的时候发生的事情也是上下文环境变量this的替换,在myRect函数体中this肯定是指向类myRect对象的实例了,然而用这个this作为上下文环境变量调用名字叫Rect方法,即类Rect的构造函数。于是此时调用Rect时候对this的赋值属性和方法都实际上是对一个myRect的对象进行。所以说尽管call和apply并不是仅仅为了继承而新增的方法,但用它们可以模拟继承。
  对象冒充继承就是这么一回事,它可以实现多重继承,只要重复做这一套赋值的流程就可以了。不过目前真正大规模使用得并不多,为什么呢?因为它有一个明显的性能缺陷,这就要说道OO的概念了,我们说对象是成员+成员方法的集合,构造对象实例的时候,这些实例只需要拥有各自的成员变量就可以了,成员方法只是一段对变量操作的可执行文本区域而已,这段区域不用为每个实例而复制一份,所有的实例都可以共享。现在回到Js利用对象冒充模拟的继承里,所有的成员方法都是针对this而创建的,也就是所所有的实例都会拥有一份成员方法的副本,这是对内存资源的一种极度浪费。其它的缺陷比如说对象冒充无法继承prototype域的变量和方法就不用提了,笔者认为前一个致命缺陷就已经足够。不过,我们还是需要理解它,特别是父类的属性和方法是如何继承下来的原理,对于理解Js继承很重要。

(二)原型方式 

  第二种继承方式是原型方式,所谓原型方式的继承,是指利用了prototype或者说以某种方式覆盖了prototype,从而达到属性方法复制的目的。其实现方式有很多中,可能不同框架多少会有一点区别,但是我们把握住原理,就不会有任何不理解的地方了。看一个例子(某一种实现):
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function Person(){  
  2.     this.name = “Mike”;  
  3.     this.sayGoodbye = function(){alert(“GoodBye!”);};  
  4. }  
  5.   
  6. Person.prototype.sayHello = function(){alert(”Hello!”);};  
  7.   
  8. function Student(){}  
  9.   
  10. Student.prototype = new Person();  
function Person(){
    this.name = “Mike”;
    this.sayGoodbye = function(){alert(“GoodBye!”);};
}

Person.prototype.sayHello = function(){alert(”Hello!”);};

function Student(){}

Student.prototype = new Person();

  关键是对最后一句Student原型属性赋值为Person类构造的对象,这里笔者解释一下父类的属性和方法是如何copy到子类上的。Js对象在读取某个对象属性的时候,总是先查看自身域的属性列表,如果有就返回否则去读取prototype域(每个对象共享构造对象的类的prototype域所有属性和方法),如果找到就返回,由于prototype可以指向别的对象,所以Js解释器会递归的去查找prototype域指向对象的prototype域,直到prototype为本身,查找变成了一种循环,就停止,此时还没找到就成undefined了。 
  这样看来,最后一句发生的效果就是将父类所有属性和方法连接到子类的prototype域上,这样子类就继承了父类所有的属性和方法,包括name、sayGoodbye和sayHello。这里与其把最后一句看成一种赋值,不如理解成一种指向关系更好一点。这种原型继承的缺陷也相当明显,就是继承时父类的构造函数时不能带参数,因为对子类prototype域的修改是在声明子类对象之后才能进行,用子类构造函数的参数去初始化父类属性是无法实现的,如下所示:
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function Person(name){  
  2.     this.name = name;  
  3. }  
  4.   
  5. function Student(name,id){  
  6.     this.id = id;  
  7. }  
  8.   
  9. Student.prototype = new Person(this.name);  
function Person(name){
    this.name = name;
}

function Student(name,id){
    this.id = id;
}

Student.prototype = new Person(this.name);

  两种继承方式已经讲完了,如果我们理解了两种方式下子类如何把父类的属性和方法“抓取”下来,就可以自由组合各自的利弊,来实现真正合理的Js继承。下面是个人总结的一种综合方式:
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function Person(name){  
  2.     this.name = name;  
  3. }  
  4.   
  5. Person.prototype.sayHello = function(){alert(this.name+“say Hello!”);};  
  6.   
  7. function Student(name,id){  
  8.     Person.call(this,name);  
  9.     this.id = id;  
  10. }  
  11.   
  12. Student.prototype = new Person();  
  13. Student.prototype.show = function(){  
  14.     alert(“Name is:”+ this.name+” and Id is:”+this.id);  
  15. }  
function Person(name){
    this.name = name;
}

Person.prototype.sayHello = function(){alert(this.name+“say Hello!”);};

function Student(name,id){
    Person.call(this,name);
    this.id = id;
}

Student.prototype = new Person();
Student.prototype.show = function(){
    alert(“Name is:”+ this.name+” and Id is:”+this.id);
}

  总结就是利用对象冒充机制的call方法把父类的属性给抓取下来,而成员方法尽量写进被所有对象实例共享的prototype域中,以防止方法副本重复创建。然后子类继承父类prototype域来抓取下来所有的方法。如想彻底理清这些调用链的关系,推荐大家多关注Js中prototype的constructor和对象的constructor属性



 

继承2

老生常谈--Js继承小结 一直以来,对Js的继承有所认识,但是认识不全面,没什么深刻印象。于是,经常性的浪费很多时间重新看博文学习继承,今天工作不是特别忙, 有幸看到了http://www.slideshare.net/stoyan/javascript-patterns?from_search=9 (该博文作者同样是《Javascript Patterns》一书的作者, 效力于Yahoo,是YSlow 的架构者和smush.it的作者),在此,自己做一些小结和笔录以免多次重复学习。 js继承:

/*******继承1:复制父亲对象所有属性-->子对象**********/

[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function extend(parent, child){  
  2.     var child = child || {};  
  3.     for(var prop in parent){  
  4.         child[prop] = parent[prop];  
  5.     }  
  6.     return child;  
  7. }  
function extend(parent, child){
	var child = child || {};
	for(var prop in parent){
		child[prop] = parent[prop];
	}
	return child;
}

/*******混合继承:从多个对象中继承****************/

[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function mixInThese(){  
  2.     var args = arguments,child = {};  
  3.     for(var i = 0, len = args.length; i < len; i++){  
  4.         for(var prop in args[i]){  
  5.             child[prop] = args[i][prop];  
  6.         }  
  7.     }  
  8.     return child;  
  9. }  
  10. var cake = mixInThese( {"oil": 3, "button": 4}, {"weight": 34}, {"tasty""sweet"});  
  11. console.log(cake);  
function mixInThese(){
    var args = arguments,child = {};
    for(var i = 0, len = args.length; i < len; i++){
        for(var prop in args[i]){
            child[prop] = args[i][prop];
        }
    }
    return child;
}
var cake = mixInThese( {"oil": 3, "button": 4}, {"weight": 34}, {"tasty": "sweet"});
console.log(cake);
 
 

/*************经典继承 原型继承 ES标准推荐 继承方式1***************************/

[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function inherit(parent, child){  
  2.     child.prototype = new Parent();   
  3. }  
function inherit(parent, child){
    child.prototype = new Parent(); 
}
/*************借用构造函数 继承方式2****************************************/
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function Child(){  
  2.     Parent.apply(this, arguments);  
  3.     //anything else   
  4. }  
function Child(){
    Parent.apply(this, arguments);
    //anything else
}
优点:创建对象的时候,可以传递参数到父亲对象

缺点:没有继承Prototype原型链上的属性

/*************借用构造函数 + 原型继承 继承方式3******************************/

[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function Child(){  
  2.     Parent.apply(this, arguments);  
  3. }  
  4. Child.prototype = new Parent();  
function Child(){
    Parent.apply(this, arguments);
}
Child.prototype = new Parent();
/**************父子对象共用同一份prototype* 继承方式4*********************************/
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function inherit(parent, child){  
  2.     child.prototype = child.prototype;  
  3. };  
function inherit(parent, child){
    child.prototype = child.prototype;
};
优点:父子对象共用同一份prototype

缺点:父子对象共用同一份prototype

/*************只继承prototype上的属性(父子对象不共用同一份prototype) 继承方式5************/

[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function inherit(parent, child){  
  2.     function F(){}  
  3.     F.prototype = new parent();  
  4.     child.prototype = new F();  
  5.     child.uber = parent.prototype;  
  6.     child.prototype.constructor = child;  
  7. }  
function inherit(parent, child){
    function F(){}
    F.prototype = new parent();
    child.prototype = new F();
    child.uber = parent.prototype;
    child.prototype.constructor = child;
}
基于原型的继承总结:

1.没有像类(Class-Like)一样的构造函数.2.对象和对象之间直接通过原型实现继承(而不像其他语言中的类和类之间的继承)。


 


 

猜你喜欢

转载自dongxylove.iteye.com/blog/2249566
OOP