JavaScript模式读书笔记 第6章 代码复用模式
主要使用代码继承来完成复用。
1,使用类式继承。
-1,类式继承:按照类的方式来实现继承,即所谓的类式。
-2,类式继承:通过构造函数(child)获取来自parent的属性,从而创建对象。
<script>//parentfunction Parent(name){this.name = name || 'Adam';}Parent.prototype.say = function(){return this.name;}//childfunction Child(name){}//此处实现继承,需要自己实现inherit(Child, Parent);</script>
-3,默认模式
//默认模式function inherit(C, P){C.prototype = new P();}var kid = new Child();console.log(kid.say());//输出Adam
-4,借用构造函数
借用父类构造函数,它传递子对象以绑定到this,并且还转发任意参数。
<script>//父构造函数function Article(){this.tags = ['js', 'css'];}var article = new Article();function BlogPost(){}BlogPost.prototype = article;//获取到对应对象的一个引用var blog = new BlogPost();function StaticPost(){Article.call(this);//获取到对应对象成员的副本,相当于在本对象中生成同样的一个成员变量}var page = new StaticPost();console.log(article.hasOwnProperty('tags'));//trueconsole.log(blog.hasOwnProperty('tags'));//falseconsole.log(page.hasOwnProperty('tags'));//true</script>
-5,借用和设置原型
<script>function Child(a, b, c, d){Parent.apply(this, arguments);//通过借用获取到父类的成员变量}Child.prototype = new Parent();//通过此处获父类的方法</script>
<script>function Parent(name){this.name = name || "Tom";}Parent.prototype.say = function(){return this.name;}function Child(name){Parent.apply(this, arguments);}Child.prototype = new Parent();var kid = new Child("Child");console.log(kid.name);//childconsole.log(kid.say());//childdelete kid.name;console.log(kid.say());//Tom</script>
-6,共享原型
function inherit(C, P){C.prototype = P.prototype;}
如果继承链下方的某个子类修改原型,那么会影响到所有原型链上的对象。
-7,临时构造函数
function inherit(C, P){var F = function(){};F.prototype = P.prototype;C.prototype = new F();}
-8,Klass
a. 都有一套关于如何命名类方法的公约。
b. 存在从其他类所继承的类。
c.在子类中可以访问父类或超类。
<script>var klass = function(Parent, props){var Child, F, i;//1. 新构造函数Child = function(){if(Child.uber && Child.uber.hasOwnProperty("_construct")){Child.uber._construct.apply(this, arguments);}if(Child.prototype.hasOwnProperty("_construct")){Child.prototype._construct.apply(this, arguments);}};//2. 继承Parent = Parent || Object;F = function(){};F.prototype = Parent.prototype;Child.prototype = new Child();Child.uber = Parent.prototype;Child.prototype.constructor = Child;//3.添加实现方法for(i in props){if(props.hasOwnProperty(i)){Child.prototype[i]= props[i];}}return Child;};</script>
代码复用才是目的,继承只是实现这一目标的方法之一。
欢迎转载,但转载请注明原文链接[博客园: http://www.cnblogs.com/jingLongJun/]
[CSDN博客:http://blog.csdn.net/mergades]。
如相关博文涉及到版权问题,请联系本人。
[CSDN博客:http://blog.csdn.net/mergades]。
如相关博文涉及到版权问题,请联系本人。

浙公网安备 33010602011771号