来源:http://blog.csdn.net/wll525775008/article/details/17308033
js不像别的语言,他是没有class的,但却是无处不对象的。我们可以通过很多方法模拟构建类以及继承等。
先来捋一下js对象的创建吧:
//第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());
//第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 ) );
- //第3种写法
- var Circle = new Object();
- Circle.PI = 3.14159;
- Circle.Area = function( r ) {
- return this.PI * r * r;
- }
- 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 ) );
- //第4种写法
- var Circle={
- "PI":3.14159,
- "area":function(r){
- return this.PI * r * r;
- }
- };
- alert( Circle.area(1.0) );
//第4种写法 var Circle={ "PI":3.14159, "area":function(r){ return this.PI * r * r; } }; alert( 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) );
//第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的继承
Js的继承在很多书里面细致的分了很多种类型和实现方式,大体上就是两种:对象冒充、原型方式。这两种方式各有优点和缺陷,这里我先列举出来,再从底层分析区别:
(一)对象冒充
- 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)};
- }
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实现的对象冒充继承。
- 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());
- }
- }
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方法调用的时候发生的事情也是上下文环境变量this的替换,在myRect函数体中this肯定是指向类myRect对象的实例了,然而用这个this作为上下文环境变量调用名字叫Rect方法,即类Rect的构造函数。于是此时调用Rect时候对this的赋值属性和方法都实际上是对一个myRect的对象进行。所以说尽管call和apply并不是仅仅为了继承而新增的方法,但用它们可以模拟继承。
对象冒充继承就是这么一回事,它可以实现多重继承,只要重复做这一套赋值的流程就可以了。不过目前真正大规模使用得并不多,为什么呢?因为它有一个明显的性能缺陷,这就要说道OO的概念了,我们说对象是成员+成员方法的集合,构造对象实例的时候,这些实例只需要拥有各自的成员变量就可以了,成员方法只是一段对变量操作的可执行文本区域而已,这段区域不用为每个实例而复制一份,所有的实例都可以共享。现在回到Js利用对象冒充模拟的继承里,所有的成员方法都是针对this而创建的,也就是所所有的实例都会拥有一份成员方法的副本,这是对内存资源的一种极度浪费。其它的缺陷比如说对象冒充无法继承prototype域的变量和方法就不用提了,笔者认为前一个致命缺陷就已经足够。不过,我们还是需要理解它,特别是父类的属性和方法是如何继承下来的原理,对于理解Js继承很重要。
(二)原型方式
第二种继承方式是原型方式,所谓原型方式的继承,是指利用了prototype或者说以某种方式覆盖了prototype,从而达到属性方法复制的目的。其实现方式有很多中,可能不同框架多少会有一点区别,但是我们把握住原理,就不会有任何不理解的地方了。看一个例子(某一种实现):- function Person(){
- this.name = “Mike”;
- this.sayGoodbye = function(){alert(“GoodBye!”);};
- }
- Person.prototype.sayHello = function(){alert(”Hello!”);};
- function Student(){}
- 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了。
- function Person(name){
- this.name = name;
- }
- function Student(name,id){
- this.id = id;
- }
- 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继承。下面是个人总结的一种综合方式:
- 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);
- }
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:复制父亲对象所有属性-->子对象**********/
- function extend(parent, child){
- var child = child || {};
- for(var prop in parent){
- child[prop] = parent[prop];
- }
- return child;
- }
function extend(parent, child){ var child = child || {}; for(var prop in parent){ child[prop] = parent[prop]; } return child; }
/*******混合继承:从多个对象中继承****************/
- 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);
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***************************/
- function inherit(parent, child){
- child.prototype = new Parent();
- }
function inherit(parent, child){ child.prototype = new Parent(); }
/*************借用构造函数 继承方式2****************************************/
- function Child(){
- Parent.apply(this, arguments);
- //anything else
- }
function Child(){ Parent.apply(this, arguments); //anything else }
优点:创建对象的时候,可以传递参数到父亲对象
缺点:没有继承Prototype原型链上的属性
/*************借用构造函数 + 原型继承 继承方式3******************************/
- function Child(){
- Parent.apply(this, arguments);
- }
- Child.prototype = new Parent();
function Child(){ Parent.apply(this, arguments); } Child.prototype = new Parent();
/**************父子对象共用同一份prototype* 继承方式4*********************************/
- function inherit(parent, child){
- child.prototype = child.prototype;
- };
function inherit(parent, child){ child.prototype = child.prototype; };
优点:父子对象共用同一份prototype
缺点:父子对象共用同一份prototype
/*************只继承prototype上的属性(父子对象不共用同一份prototype) 继承方式5************/
- function inherit(parent, child){
- function F(){}
- F.prototype = new parent();
- child.prototype = new F();
- child.uber = parent.prototype;
- child.prototype.constructor = child;
- }
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.对象和对象之间直接通过原型实现继承(而不像其他语言中的类和类之间的继承)。