《Javascript 设计模式 老版》-读书笔记

第一章  富有表现力的javascript

一、Function添加新方法

  如果在Function对象中添加一人新方法可以这样写:Function.porototype.method("方法名",  function(){  执行的内容  })

1 <script>
2     var Anim = function(){}
3 
4     // 为Anim对象添加方法
5     Anim.mothod("start", function(){ ... }).
6             mothod("stop", function(){ ... });
7 </script>

二、使用设计模式的好处

  1、可维护性好:降低了模块间的耦合度.

  2、性能:某些模式是起优化的作用,提高运行速度.

第四章  继承

一、继承类型

  继承可以分成原型继承和类式继承,原型继承要比类继承更节省内存 

1、类式继承

 1 <script>
 2     function Peron (name) {
 3         this.name = name;
 4     }
 5 
 6     Peron.prototype.getName = function(){
 7         console.log(this.name);
 8     }
 9 
10     Peron.prototype.setName = function(name){
11         this.name = name;
12     }
13 
14     var reader = new Peron("haha");     // 可以继承对象的属性和方法
15     alert(reader.name)          // 哈哈
16     reader.getName();
17     reader.setName("lulu");
18     reader.getName();
19     alert(reader.name);         // lulu
20 </script>

2、原型继承

 1 <input type="text" id="oName" value="">
 2 <input type="text" id="oAge" value="">
 3 
 4 <script>
 5     function $(id) {
 6         return document.getElementById(id);
 7     }
 8 
 9     // 定义一个基类
10     var Anim = function(name, age){
11         this.name = name;
12         this.age = age;
13     }
14 
15     Anim.prototype.printContext = function(){        // Anim的方法输出name和age
16         console.log(this.name + "," + this.age);
17     }
18 
19     // 实例化对象
20     var pop1 = new Anim("siguang", 30);
21     pop1.printContext();
22 
23 
24     // 创建对象
25     var StartAnim = function(name, age, read){
26         this.name = name;
27         this.age = age;
28         this.read = read;
29     }
30 
31     // StartAnim对象继承Anim的属性和方法
32     StartAnim.prototype = new Anim();
33 
34     // 重写printContent方法,输出name、age、read,如果不重写方法则会调用Anim中的printConext()方法
35     StartAnim.prototype.printContext = function(){
36         console.log(this.name + "," + this.age + "," + this.read);
37     }
38 
39     // 增加一个方法
40     StartAnim.prototype.extStart = function(){
41         this.printContext();
42 
43         var sName = $("oName");
44         var sAge = $("oAge");
45 
46         sName.value = this.name;
47         sAge.value = this.age;
48     }
49 
50     var oAnim = new StartAnim("lulu", 28, "哈哈");
51     oAnim.extStart();
52 
53     // 实例化对象
54     var pop2 = new Anim("1111", 322);
55     pop2.printContext();
56 </script>
原文地址:https://www.cnblogs.com/couxiaozi1983/p/3983009.html