JAVA学习点点滴滴

用开放的脑子去闯荡;用开阔的视野去拼搏;用平和的身心去磨练;用美好的理想去追求!

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  18 随笔 :: 1 文章 :: 2 评论 :: 0 Trackbacks

2007年1月7日 #

创建型模式

1、FACTORY—追MM少不了请吃饭了,麦当劳的鸡翅和肯德基的鸡翅都是MM爱吃的东西,虽然口味有所不同,但不管你带MM去麦当劳或肯德基,只管向服务员说“来四个鸡翅”就行了。麦当劳和肯德基就是生产鸡翅的Factory

工厂模式:客户类和工厂类分开。消费者任何时候需要某种产品,只需向工厂请求即可。消费者无须修改就可以接纳新产品。缺点是当产品修改时,工厂类也要做相应的修改。如:如何创建及如何向客户端提供。

2、BUILDER—MM最爱听的就是“我爱你”这句话了,见到不同地方的MM,要能够用她们的方言跟她说这句话哦,我有一个多种语言翻译机,上面每种语言都有一个按键,见到MM我只要按对应的键,它就能够用相应的语言说出“我爱你”这句话了,国外的MM也可以轻松搞掂,这就是我的“我爱你”builder。(这一定比美军在伊拉克用的翻译机好卖)

建造模式:将产品的内部表象和产品的生成过程分割开来,从而使一个建造过程生成具有不同的内部表象的产品对象。建造模式使得产品内部表象可以独立的变化,客户不必知道产品内部组成的细节。建造模式可以强制实行一种分步骤进行的建造过程。

3、FACTORY METHOD—请MM去麦当劳吃汉堡,不同的MM有不同的口味,要每个都记住是一件烦人的事情,我一般采用Factory Method模式,带着MM到服务员那儿,说“要一个汉堡”,具体要什么样的汉堡呢,让MM直接跟服务员说就行了。

工厂方法模式:核心工厂类不再负责所有产品的创建,而是将具体创建的工作交给子类去做,成为一个抽象工厂角色,仅负责给出具体工厂类必须实现的接口,而不接触哪一个产品类应当被实例化这种细节。

4、PROTOTYPE—跟MM用QQ聊天,一定要说些深情的话语了,我搜集了好多肉麻的情话,需要时只要copy出来放到QQ里面就行了,这就是我的情话prototype了。(100块钱一份,你要不要)

原始模型模式:通过给出一个原型对象来指明所要创建的对象的类型,然后用复制这个原型对象的方法创建出更多同类型的对象。原始模型模式允许动态的增加或减少产品类,产品类不需要非得有任何事先确定的等级结构,原始模型模式适用于任何的等级结构。缺点是每一个类都必须配备一个克隆方法。

5、SINGLETON—俺有6个漂亮的老婆,她们的老公都是我,我就是我们家里的老公Sigleton,她们只要说道“老公”,都是指的同一个人,那就是我(刚才做了个梦啦,哪有这么好的事)

单例模式:单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例单例模式。单例模式只应在有真正的“单一实例”的需求时才可使用。

结构型模式

6、ADAPTER—在朋友聚会上碰到了一个美女Sarah,从香港来的,可我不会说粤语,她不会说普通话,只好求助于我的朋友kent了,他作为我和Sarah之间的Adapter,让我和Sarah可以相互交谈了(也不知道他会不会耍我)

适配器(变压器)模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口原因不匹配而无法一起工作的两个类能够一起工作。适配类可以根据参数返还一个合适的实例给客户端。

7、BRIDGE—早上碰到MM,要说早上好,晚上碰到MM,要说晚上好;碰到MM穿了件新衣服,要说你的衣服好漂亮哦,碰到MM新做的发型,要说你的头发好漂亮哦。不要问我“早上碰到MM新做了个发型怎么说”这种问题,自己用BRIDGE组合一下不就行了

桥梁模式:将抽象化与实现化脱耦,使得二者可以独立的变化,也就是说将他们之间的强关联变成弱关联,也就是指在一个软件系统的抽象化和实现化之间使用组合/聚合关系而不是继承关系,从而使两者可以独立的变化。

8、COMPOSITE—Mary今天过生日。“我过生日,你要送我一件礼物。”“嗯,好吧,去商店,你自己挑。”“这件T恤挺漂亮,买,这条裙子好看,买,这个包也不错,买。”“喂,买了三件了呀,我只答应送一件礼物的哦。”“什么呀,T恤加裙子加包包,正好配成一套呀,小姐,麻烦你包起来。”“……”,MM都会用Composite模式了,你会了没有?

合成模式:合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式就是一个处理对象的树结构的模式。合成模式把部分与整体的关系用树结构表示出来。合成模式使得客户端把一个个单独的成分对象和由他们复合而成的合成对象同等看待。

9、DECORATOR—Mary过完轮到Sarly过生日,还是不要叫她自己挑了,不然这个月伙食费肯定玩完,拿出我去年在华山顶上照的照片,在背面写上“最好的的礼物,就是爱你的Fita”,再到街上礼品店买了个像框(卖礼品的MM也很漂亮哦),再找隔壁搞美术设计的Mike设计了一个漂亮的盒子装起来……,我们都是Decorator,最终都在修饰我这个人呀,怎么样,看懂了吗?

装饰模式:装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案,提供比继承更多的灵活性。动态给一个对象增加功能,这些功能可以再动态的撤消。增加由一些基本功能的排列组合而产生的非常大量的功能。

10、FACADE—我有一个专业的Nikon相机,我就喜欢自己手动调光圈、快门,这样照出来的照片才专业,但MM可不懂这些,教了半天也不会。幸好相机有Facade设计模式,把相机调整到自动档,只要对准目标按快门就行了,一切由相机自动调整,这样MM也可以用这个相机给我拍张照片了。

门面模式:外部与一个子系统的通信必须通过一个统一的门面对象进行。门面模式提供一个高层次的接口,使得子系统更易于使用。每一个子系统只有一个门面类,而且此门面类只有一个实例,也就是说它是一个单例模式。但整个系统可以有多个门面类。

11、FLYWEIGHT—每天跟MM发短信,手指都累死了,最近买了个新手机,可以把一些常用的句子存在手机里,要用的时候,直接拿出来,在前面加上MM的名字就可以发送了,再不用一个字一个字敲了。共享的句子就是Flyweight,MM的名字就是提取出来的外部特征,根据上下文情况使用。

享元模式:FLYWEIGHT在拳击比赛中指最轻量级。享元模式以共享的方式高效的支持大量的细粒度对象。享元模式能做到共享的关键是区分内蕴状态和外蕴状态。内蕴状态存储在享元内部,不会随环境的改变而有所不同。外蕴状态是随环境的改变而改变的。外蕴状态不能影响内蕴状态,它们是相互独立的。将可以共享的状态和不可以共享的状态从常规类中区分开来,将不可以共享的状态从类里剔除出去。客户端不可以直接创建被共享的对象,而应当使用一个工厂对象负责创建被共享的对象。享元模式大幅度的降低内存中对象的数量。

12、PROXY—跟MM在网上聊天,一开头总是“hi,你好”,“你从哪儿来呀?”“你多大了?”“身高多少呀?”这些话,真烦人,写个程序做为我的Proxy吧,凡是接收到这些话都设置好了自动的回答,接收到其他的话时再通知我回答,怎么样,酷吧。

代理模式:代理模式给某一个对象提供一个代理对象,并由代理对象控制对源对象的引用。代理就是一个人或一个机构代表另一个人或者一个机构采取行动。某些情况下,客户不想或者不能够直接引用一个对象,代理对象可以在客户和目标对象直接起到中介的作用。客户端分辨不出代理主题对象与真实主题对象。代理模式可以并不知道真正的被代理对象,而仅仅持有一个被代理对象的接口,这时候代理对象不能够创建被代理对象,被代理对象必须有系统的其他角色代为创建并传入。

行为模式

13、CHAIN OF RESPONSIBLEITY—晚上去上英语课,为了好开溜坐到了最后一排,哇,前面坐了好几个漂亮的MM哎,找张纸条,写上“Hi,可以做我的女朋友吗?如果不愿意请向前传”,纸条就一个接一个的传上去了,糟糕,传到第一排的MM把纸条传给老师了,听说是个老处女呀,快跑!

责任链模式:在责任链模式中,很多对象由每一个对象对其下家的引用而接

起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。客户并不知道链上的哪一个对象最终处理这个请求,系统可以在不影响客户端的情况下动态的重新组织链和分配责任。处理者有两个选择:承担责任或者把责任推给下家。一个请求可以最终不被任何接收端对象所接受。
14、COMMAND—俺有一个MM家里管得特别严,没法见面,只好借助于她弟弟在我们俩之间传送信息,她对我有什么指示,就写一张纸条让她弟弟带给我。这不,她弟弟又传送过来一个COMMAND,为了感谢他,我请他吃了碗杂酱面,哪知道他说:“我同时给我姐姐三个男朋友送COMMAND,就数你最小气,才请我吃面。”,:-(

命令模式:命令模式把一个请求或者操作封装到一个对象中。命令模式把发出命令的责任和执行命令的责任分割开,委派给不同的对象。命令模式允许请求的一方和发送的一方独立开来,使得请求的一方不必知道接收请求的一方的接口,更不必知道请求是怎么被接收,以及操作是否执行,何时被执行以及是怎么被执行的。系统支持命令的撤消。

15、INTERPRETER—俺有一个《泡MM真经》,上面有各种泡MM的攻略,比如说去吃西餐的步骤、去看电影的方法等等,跟MM约会时,只要做一个Interpreter,照着上面的脚本执行就可以了。

解释器模式:给定一个语言后,解释器模式可以定义出其文法的一种表示,并同时提供一个解释器。客户端可以使用这个解释器来解释这个语言中的句子。解释器模式将描述怎样在有了一个简单的文法后,使用模式设计解释这些语句。在解释器模式里面提到的语言是指任何解释器对象能够解释的任何组合。在解释器模式中需要定义一个代表文法的命令类的等级结构,也就是一系列的组合规则。每一个命令对象都有一个解释方法,代表对命令对象的解释。命令对象的等级结构中的对象的任何排列组合都是一个语言。

 

16、ITERATOR—我爱上了Mary,不顾一切的向她求婚。

Mary:“想要我跟你结婚,得答应我的条件”

我:“什么条件我都答应,你说吧”

Mary:“我看上了那个一克拉的钻石”

我:“我买,我买,还有吗?”

Mary:“我看上了湖边的那栋别墅”

我:“我买,我买,还有吗?”

Mary:“你的小弟弟必须要有50cm长”

我脑袋嗡的一声,坐在椅子上,一咬牙:“我剪,我剪,还有吗?”

……

迭代子模式:迭代子模式可以顺序访问一个聚集中的元素而不必暴露聚集的内部表象。多个对象聚在一起形成的总体称之为聚集,聚集对象是能够包容一组对象的容器对象。迭代子模式将迭代逻辑封装到一个独立的子对象中,从而与聚集本身隔开。迭代子模式简化了聚集的界面。每一个聚集对象都可以有一个或一个以上的迭代子对象,每一个迭代子的迭代状态可以是彼此独立的。迭代算法可以独立于聚集角色变化。

17、MEDIATOR—四个MM打麻将,相互之间谁应该给谁多少钱算不清楚了,幸亏当时我在旁边,按照各自的筹码数算钱,赚了钱的从我这里拿,赔了钱的也付给我,一切就OK啦,俺得到了四个MM的电话。

调停者模式:调停者模式包装了一系列对象相互作用的方式,使得这些对象不必相互明显作用。从而使他们可以松散偶合。当某些对象之间的作用发生改变时,不会立即影响其他的一些对象之间的作用。保证这些作用可以彼此独立的变化。调停者模式将多对多的相互作用转化为一对多的相互作用。调停者模式将对象的行为和协作抽象化,把对象在小尺度的行为上与其他对象的相互作用分开处理。

18、MEMENTO—同时跟几个MM聊天时,一定要记清楚刚才跟MM说了些什么话,不然MM发现了会不高兴的哦,幸亏我有个备忘录,刚才与哪个MM说了什么话我都拷贝一份放到备忘录里面保存,这样可以随时察看以前的记录啦。

备忘录模式:备忘录对象是一个用来存储另外一个对象内部状态的快照的对象。备忘录模式的用意是在不破坏封装的条件下,将一个对象的状态捉住,并外部化,存储起来,从而可以在将来合适的时候把这个对象还原到存储起来的状态。

19、OBSERVER—想知道咱们公司最新MM情报吗?加入公司的MM情报邮件组就行了,tom负责搜集情报,他发现的新情报不用一个一个通知我们,直接发布给邮件组,我们作为订阅者(观察者)就可以及时收到情报啦

观察者模式:观察者模式定义了一种一队多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使他们能够自动更新自己。

20、STATE—跟MM交往时,一定要注意她的状态哦,在不同的状态时她的行为会有不同,比如你约她今天晚上去看电影,对你没兴趣的MM就会说“有事情啦”,对你不讨厌但还没喜欢上的MM就会说“好啊,不过可以带上我同事么?”,已经喜欢上你的MM就会说“几点钟?看完电影再去泡吧怎么样?”,当然你看电影过程中表现良好的话,也可以把MM的状态从不讨厌不喜欢变成喜欢哦。

状态模式:状态模式允许一个对象在其内部状态改变的时候改变行为。这个对象看上去象是改变了它的类一样。状态模式把所研究的对象的行为包装在不同的状态对象里,每一个状态对象都属于一个抽象状态类的一个子类。状态模式的意图是让一个对象在其内部状态改变的时候,其行为也随之改变。状态模式需要对每一个系统可能取得的状态创立一个状态类的子类。当系统的状态变化时,系统便改变所选的子类。

   21、STRATEGY—跟不同类型的MM约会,要用不同的策略,有的请电影比较好,有的则去吃小吃效果不错,有的去海边浪漫最合适,单目的都是为了得到MM的芳心,我的追MM锦囊中有好多Strategy哦。

策略模式:策略模式针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。策略模式把行为和环境分开。环境类负责维持和查询行为类,各种算法在具体的策略类中提供。由于算法和环境独立开来,算法的增减,修改都不会影响到环境和客户端。

22、TEMPLATE METHOD——看过《如何说服女生上床》这部经典文章吗?女生从认识到上床的不变的步骤分为巧遇、打破僵局、展开追求、接吻、前戏、动手、爱抚、进去八大步骤(Template method),但每个步骤针对不同的情况,都有不一样的做法,这就要看你随机应变啦(具体实现);

模板方法模式:模板方法模式准备一个抽象类,将部分逻辑以具体方法以及具体构造子的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现。先制定一个顶级逻辑框架,而将逻辑的细节留给具体的子类去实现。

23、VISITOR—情人节到了,要给每个MM送一束鲜花和一张卡片,可是每个MM送的花都要针对她个人的特点,每张卡片也要根据个人的特点来挑,我一个人哪搞得清楚,还是找花店老板和礼品店老板做一下Visitor,让花店老板根据MM的特点选一束花,让礼品店老板也根据每个人特点选一张卡,这样就轻松多了;

访问者模式:访问者模式的目的是封装一些施加于某种数据结构元素之上的操作。一旦这些操作需要修改的话,接受这个操作的数据结构可以保持不变。访问者模式适用于数据结构相对未定的系统,它把数据结构和作用于结构上的操作之间的耦合解脱开,使得操作集合可以相对自由的演化。访问者模式使得增加新的操作变的很容易,就是增加一个新的访问者类。访问者模式将有关的行为集中到一个访问者对象中,而不是分散到一个个的节点类中。当使用访问者模式时,要将尽可能多的对象浏览逻辑放在访问者类中,而不是放到它的子类中。访问者模式可以跨过几个类的等级结构访问属于不同的等级结构的成员类。

http://java.ccidnet.com/art/3749/20060622/586221_3.html

 

posted @ 2007-01-27 23:05 海思 阅读(254) | 评论 (0)编辑 收藏

Object Hierarchy and Inheritance in JavaScript

JavaScript is an object-oriented language based on prototypes, rather than, as is common, being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values. This paper attempts to clarify the situation. If you're interested in precise details of how this all works, you can read the ECMA-262 JavaScript language specification (as a PDF file or a Microsoft Word self-extracting binary).

This paper assumes that you're already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects. For information on this subject, see Chapter 10, "Object Model," in the JavaScript Guide.

The sections in this paper are:

Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances. A class defines all of the properties (considering methods and fields in Java, or members in C++, to be properties) that characterize a certain set of objects. A class is an abstract thing, rather than any particular member of the set of objects it describes. For example, the Employee class could represent the set of all employees. An instance, on the other hand, is the instantiation of a class; that is, one of its members. For example, Victoria could be an instance of the Employee class, representing a particular individual as an employee. An instance has exactly the properties of its parent class (no more, no less).

A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or even at runtime. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties.

In class-based languages, you define a class in a separate class definition. In that definition you can specify special methods, called constructors, to use to create instances of the class. A constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. You use the new operator in association with the constructor method to create class instances.

JavaScript follows a similar model, but does not have a class definition separate from the constructor. Instead, you define a constructor function to create objects with a particular initial set of properties and values. Any JavaScript function can be used as a constructor. You use the new operator with a constructor function to create a new object.

In a class-based language, you create a hierarchy of classes through the class definitions. In a class definition, you can specify that the new class is a subclass of an already existing class. The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones. For example, assume the Employee class includes only name and dept properties and Manager is a subclass of Employee that adds the reports property. In this case, an instance of the Manager class would have all three properties: name, dept, and reports.

JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the Employee-Manager example, but you use slightly different terminology. First you define the Employee constructor function, specifying the name and dept properties. Next, you define the Manager constructor function, specifying the reports property. Finally, you assign a new Employee object as the prototype for the Manager constructor function. Then, when you create a new Manager, it inherits the name and dept properties from the Employee object.

In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at runtime. You cannot change the number or the type of properties of a class after you define the class. In JavaScript, however, at runtime you can add or remove properties from any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property.

Table 1 gives a short summary of some of these differences. The rest of this paper describes the details of using JavaScript constructors and prototypes to create an object hierarchy and compares this to how you would do it in Java.

Table 1 Comparison of class-based (Java) and prototype-based (JavaScript) object systems

Class-based (Java) Prototype-based (JavaScript)
Class and instance are distinct entities.

All objects are instances.

Define a class with a class definition; instantiate a class with constructor methods.

Define and create a set of objects with constructor functions.

Create a single object with the new operator.

Same.

Construct an object hierarchy by using class definitions to define subclasses of existing classes.

Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.

Inherit properties by following the class chain.

Inherit properties by following the prototype chain.

Class definition specifies all properties of all instances of a class. No way to add properties dynamically at runtime.

Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.

The Employee Example

The rest of this paper works with the simple employee hierarchy shown in Figure 1.

Figure 1    A simple object hierarchy

  • Employee has the properties name (whose value defaults to the empty string) and dept (whose value defaults to "general").
  • Manager is based on Employee. It adds the reports property (whose value defaults to an empty array, intended to have an array of Employee objects as its value).

  • WorkerBee is also based on Employee. It adds the projects property (whose value defaults to an empty array, intended to have an array of strings as its value).

  • SalesPerson is based on WorkerBee. It adds the quota property (whose value defaults to 100). It also overrides the dept property with the value "sales", indicating that all salespersons are in the same department.

  • Engineer is based on WorkerBee. It adds the machine property (whose value defaults to the empty string) and also overrides the dept property with the value "engineering".

    Creating the Hierarchy

    There are several ways you can define appropriate constructor functions to implement the Employee hierarchy. How you choose to define them depends largely on what you want to be able to do in your application. We'll get into all that later.

    For now, let's use very simple (and comparatively inflexible) definitions just to see how we get the inheritance to work. In these definitions, you can't specify any property values when you create an object. The newly-created object simply gets the default values, which you can change at a later time. Figure 2 illustrates the hierarchy with these simple definitions.

    In a real application, you would probably define constructors that allow you to provide property values at object creation time. Options for doing so are described later in "More Flexible Constructors". For now, these simple definitions let us look at how the inheritance occurs.

    Figure 2    What the definitions look like

    The simple Java and JavaScript Employee definitions below are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript and you need to create an explicit constructor method for the Java class.

    JavaScript Java
    function Employee () {
    this.name = "";
    this.dept = "general";
    }
    public class Employee {
       public String name;
       public String dept;
       public Employee () {
          this.name = "";
          this.dept = "general";
       }
    }

    The Manager and WorkerBee definitions show the difference in how you specify the next object higher in the inheritance chain. In JavaScript, you add a prototypical instance as the value of the prototype property of the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition.

    JavaScript Java
    function Manager () {
    this.reports = [];
    }
    Manager.prototype = new Employee;
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    public class Manager extends Employee {
       public Employee[] reports;
       public Manager () {
          this.reports = new Employee[0];
       }
    }
    public class WorkerBee extends Employee {
       public String[] projects;
       public WorkerBee () {
          this.projects = new String[0];
       }
    }

    The Engineer and SalesPerson definitions create objects that descend from WorkerBee and hence from Employee. An object of these types has properties of all the objects above it in the chain. In addition, these definitions override the inherited value of the dept property with new values specific to these objects.

    JavaScript Java
    function SalesPerson () {
       this.dept = "sales";
       this.quota = 100;
    }
    SalesPerson.prototype = new WorkerBee;
    function Engineer () {
       this.dept = "engineering";
       this.machine = "";
    }
    Engineer.prototype = new WorkerBee;
    public class SalesPerson extends WorkerBee {
       public double quota;
       public SalesPerson () {
          this.dept = "sales";
          this.quota = 100.0;
       }
    }
    public class Engineer extends WorkerBee {
       public String machine;
       public Engineer () {
          this.dept = "engineering";
          this.machine = "";
       }
    }

    Using these definitions, you can create instances of these objects that get the default values for their properties. Figure 3 illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects.

    NOTE: As described earlier, the term instance has a specific technical meaning in class-based languages. In these languages, an instance is an individual member of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that jane is an instance of Engineer. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript, we can use them informally to refer to objects higher or lower in the prototype chain.
    Figure 3    Creating objects with the simple definitions

    Object Properties

    This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at runtime.

    Inheriting Properties

    Assume you create the mark object as a WorkerBee as shown in Figure 3 with this statement:

    mark = new WorkerBee;
    When JavaScript sees the new operator, it creates a new generic object and passes this new object as the value of the this keyword to the WorkerBee constructor function. The constructor function explicitly sets the value of the projects property. It also sets the value of the internal __proto__ property to the value of WorkerBee.prototype. (That property name has 2 underscore characters at the front and 2 at the end.) The __proto__ property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variable mark to that object.

    This process doesn't explicitly put values in the mark object (local values) for the properties mark inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value isn't there locally, JavaScript checks the prototype chain (using the __proto__ property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object doesn't have the property. In this way, the mark object has the following properties and values:

    mark.name = "";
    mark.dept = "general";
    mark.projects = [];
    The mark object inherits values for the name and dept properties from the prototypical object in mark.__proto__. It is assigned a local value for the projects property by the WorkerBee constructor. Simply put, this gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in "Property Inheritance Revisited".

    Because these constructors don't let you supply instance-specific values, this information is generic. The property values are the default ones shared by all new objects created from WorkerBee. You can, of course, change the values of any of these properties. So, you could give specific information for mark as shown here:

    mark.name = "Doe, Mark";
    mark.dept = "admin";
    mark.projects = ["navigator"];

    Adding Properties

    In JavaScript at runtime you can add properties to any object. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you simply assign a value to the object, as in:

    mark.bonus = 3000;
    Now, the mark object has a bonus property, but no other WorkerBee has this property.

    If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a specialty property to all employees with the following statement:

    Employee.prototype.specialty = "none";
    As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none". Figure 4 shows the effect of adding this property to the Employee prototype and then overriding it for the Engineer prototype.

    Figure 4    Adding properties

    More Flexible Constructors

    The constructor functions used so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. Figure 5 shows one way to do this.

    Figure 5    Specifying properties in a constructor, take 1

    Here are the Java and JavaScript definitions for these objects.

    JavaScript Java
    function Employee (name, dept) {
    this.name = name || "";
    this.dept = dept || "general";
    }
    public class Employee {
       public String name;
       public String dept;
       public Employee () {
          this("", "general");
       }
       public Employee (name) {
          this(name, "general");
       }
       public Employee (name, dept) {
          this.name = name;
          this.dept = dept;
       }
    }
    function WorkerBee (projs) {
    this.projects = projs || [];
    }
    WorkerBee.prototype = new Employee;
    public class WorkerBee extends Employee {
       public String[] projects;
       public WorkerBee () {
          this(new String[0]);
       }
       public WorkerBee (String[] projs) {
          this.projects = projs;
       }
    }
    function Engineer (mach) {
       this.dept = "engineering";
       this.machine = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    public class Engineer extends WorkerBee {
       public String machine;
       public WorkerBee () {
          this.dept = "engineering";
          this.machine = "";
       }
       public WorkerBee (mach) {
          this.dept = "engineering";
          this.machine = mach;
       }
    }

    These JavaScript definitions use a special idiom for setting default values:

    this.name = name || "";
    The JavaScript logical OR operator (||) evaluates its first argument. If that argument is converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This paper uses this idiom for brevity; however, it can be puzzling at first glance.

    With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. As shown in Figure 5, you can use this statement to create a new Engineer:

    jane = new Engineer("belau");
    Jane's properties are now:

    jane.name == "";
    jane.dept == "general";
    jane.projects == [];
    jane.machine == "belau"
    Notice that with these definitions, you cannot specify an initial value for an inherited property such as name. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.

    So far, the constructor function has created a generic object and then specified local properties and values for the new object. You can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. Figure 6 shows these new definitions.

    Figure 6    Specifying properties in a constructor, take 2

    Let's look at one of these definitions in detail. Here's the new definition for the Engineer constructor:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    Assume we create a new Engineer object as follows:

    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    JavaScript follows these steps:

    1.   First, the new operator creates a generic object and sets its __proto__ property to Engineer.prototype.
    2.   The new operator then passes the new object to the Engineer constructor as the value of the this keyword.
    3.   Next, the constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object.
    NOTE: The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.
    4.   Next, the constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property and this value overrides the value inherited from Employee.
    5.   Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in step 1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and ["navigator", "javascript"] arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.
    6.   Upon return from the base method, the Engineer constructor initializes the object's machine property to "belau".
    7.   Upon return from the constructor, JavaScript assigns the new object to the jane variable.
    You might think that, having called the WorkerBee constructor from inside the Engineer constructor, you've set up inheritance appropriately for Engineer objects. This is not the case. Calling the WorkerBee constructor ensures that an Engineer object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the Employee or WorkerBee prototypes, those properties are not inherited by the Engineer object. For example, assume you have these statements:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    Employee.prototype.specialty = "none";
    The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    Employee.prototype.specialty = "none";
    Now the value of the jane object's specialty property is "none".

    Property Inheritance Revisited

    The preceding sections have described how constructors and prototypes provide hierarchies and inheritance in JavaScript. As with all languages, there are some subtleties that were not necessarily apparent in these earlier discussions. This section discusses some of those subtleties.

    Local versus Inherited Values

    Let's revisit property inheritance briefly. As discussed earlier, when you access an object property, JavaScript performs these steps:

    1. Check to see if the value exists locally. If it does, return that value.
    2. If there isn't a local value, check the prototype chain (using the __proto__ property).

    3. If an object in the prototype chain has a value for the specified property, return that value.

    4. If no such property is found, the object does not have the property.
    The outcome of this simple set of steps depends on how you've defined things along the way. In our original example, we had these definitions:

    function Employee () {
    this.name = "";
    this.dept = "general";
    }
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    With these definitions, assume you create amy as an instance of WorkerBee with this statement:

    amy = new WorkerBee;
    The amy object has one local property, projects. The values for the name and dept properties are not local to amy and so are gotten from the amy object's __proto__ property. Thus, amy has these property values:

    amy.name == "";
    amy.dept = "general";
    amy.projects == [];
    Now assume you change the value of the name property in the prototype associated with Employee:

    Employee.prototype.name = "Unknown"
    At first glance, you might expect that new value to propagate down to all the instances of Employee. However, it does not.

    When you create any instance of the Employee object, that instance gets a local value for the name property (the empty string). This means that when you set the WorkerBee prototype by creating a new Employee object, WorkerBee.prototype has a local value for the name property. Therefore, when JavaScript looks up the name property of the amy object (an instance of WorkerBee), JavaScript finds the local value for that property in WorkerBee.prototype. It therefore does not look farther up the chain to Employee.prototype.

    If you want to change the value of an object property at runtime and have the new value be inherited by all descendants of the object, you cannot define the property in the object's constructor function. Instead, you add it to the constructor's associated prototype. For example, assume you change the code above to the following:

    function Employee () {
       this.dept = "general";
    }
    Employee.prototype.name = "";
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    amy = new WorkerBee;
    Employee.prototype.name = "Unknown";
    In this case, the name property of amy becomes "Unknown".

    As these examples show, if you want to have default values for object properties and you want to be able to change the default values at runtime, you should set the properties in the constructor's prototype, not in the constructor function itself.

    Determining Instance Relationships

    You may want to know what objects are in the prototype chain for an object, so that you can tell from what objects this object inherits properties. In a class-based language, you might have an instanceof operator for this purpose. JavaScript does not provide instanceof, but you can write such a function yourself.

    As discussed in "Inheriting Properties", when you use the new operator with a constructor function to create a new object, JavaScript sets the __proto__ property of the new object to the value of the prototype property of the constructor function. You can use this to test the prototype chain.

    For example, assume you have the same set of definitions we've been using, with the prototypes set appropriately. Create an __proto__ object as follows:

    chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");
    With this object, the following statements are all true:

    chris.__proto__ == Engineer.prototype;
    chris.__proto__.__proto__ == WorkerBee.prototype;
    chris.__proto__.__proto__.__proto__ == Employee.prototype;
    chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;
    chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;
    Given this, you could write an instanceOf function as follows:

    function instanceOf(object, constructor) { 
       while (object != null) {
          if (object == constructor.prototype)
             return true;
          object = object.__proto__;
       }
       return false;
    }
    With this definition, the following expressions are all true:

    instanceOf (chris, Engineer)
    instanceOf (chris, WorkerBee)
    instanceOf (chris, Employee)
    instanceOf (chris, Object)
    But this expression is false:

    instanceOf (chris, SalesPerson)

    Global Information in Constructors

    When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use this definition for Employee:

    var idCounter = 1;
    function Employee (name, dept) {
       this.name = name || "";
       this.dept = dept || "general";
       this.id = idCounter++;
    }
    With this definition, when you create a new Employee, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement were:

    victoria = new Employee("Pigbert, Victoria", "pubs")
    harry = new Employee("Tschopik, Harry", "sales")
    victoria.id is 1 and harry.id is 2. At first glance that seems fine. However, idCounter gets incremented every time an Employee object is created, for whatever purpose. If you create the entire Employee hierarchy we've been working with, the Employee constructor is called every time we set up a prototype. That is, assume you have this code:

    var idCounter = 1;
    function Employee (name, dept) {
       this.name = name || "";
       this.dept = dept || "general";
       this.id = idCounter++;
    }
    function Manager (name, dept, reports) {...}
    Manager.prototype = new Employee;
    function WorkerBee (name, dept, projs) {...}
    WorkerBee.prototype = new Employee;
    function Engineer (name, projs, mach) {...}
    Engineer.prototype = new WorkerBee;
    function SalesPerson (name, projs, quota) {...}
    SalesPerson.prototype = new WorkerBee;
    mac = new Engineer("Wood, Mac");
    Further assume that the definitions we've omitted here have the base property and call the constructor above them in the prototype chain. In this case, by the time the mac object is created, mac.id is 5.

    Depending on the application, it may or may not matter that the counter has been incremented these extra times. If you care about the exact value of this counter, one possible solution involves instead using this constructor:

    function Employee (name, dept) {
       this.name = name || "";
       this.dept = dept || "general";
       if (name)
          this.id = idCounter++;
    }
    When you create an instance of Employee to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for an Employee to get an assigned id, you must specify a name for the employee. In our example, mac.id would be 1.

    No Multiple Inheritance

    Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance.

    As we've already said, inheritance of property values occurs at runtime by JavaScript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, JavaScript cannot dynamically inherit from more than one prototype chain.

    In JavaScript you can have a constructor function call more than one other constructor function within it. This gives the illusion of multiple inheritance. For example, consider the following statements:

    function Hobbyist (hobby) {
       this.hobby = hobby || "scuba";
    }
    function Engineer (name, projs, mach, hobby) {
       this.base1 = WorkerBee;
       this.base1(name, "engineering", projs);
       this.base2 = Hobbyist;
       this.base2(hobby);
       this.projects = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo")
    Further assume that the definition of WorkerBee is as we've previously seen it. In this case, the dennis object has these properties:

    dennis.name == "Doe, Dennis"
    dennis.dept == "engineering"
    dennis.projects == ["collabra"]
    dennis.machine == "hugo"
    dennis.hobby == "scuba"
    So dennis does get the hobby property from the Hobbyist constructor. However, assume you then add a property to the Hobbyist constructor's prototype:

    Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]
    The dennis object does not inherit this new property.

    Last Updated: 12/18/97 15:19:54


    Copyright © 1997 Netscape Communications Corporation

  • posted @ 2007-01-21 16:19 海思 阅读(466) | 评论 (0)编辑 收藏

    跨越边界: JavaScript 语言特性

    研究编程语言中的“丑小鸭”

    developerWorks
    文档选项
    将此页作为电子邮件发送

    将此页作为电子邮件发送

    未显示需要 JavaScript 的文档选项

    样例代码


    拓展 Tomcat 应用

    下载 IBM 开源 J2EE 应用服务器 WAS CE 新版本 V1.1


    级别: 初级

    Bruce Tate (bruce.tate@j2life.com), 总裁, RapidRed

    2007 年 1 月 18 日

    JavaScript 常被人们认为是编程语言中无足轻重的一员。这种观点的形成可以“归功”于其开发工具、复杂且不一致的面向 HTML 页面的文档对象模型以及不一致的浏览器实现。但 JavaScript 绝对不仅仅是一个玩具这么简单。在本文中,Bruce Tate 向您介绍了 JavaScript 的语言特性。

    几乎每个 Web 开发人员都曾有过诅咒 JavaScript 的经历。这个备受争议的语言受累于其复杂的称为文档对象模型 (DOM)的编程模型、糟糕的实现和调试工具以及不一致的浏览器实现。直到最近,很多开发人员还认为 Javascript 从最好的方面说是无可避免之灾祸,从最坏的方面说不过是一种玩具罢了。

    然而 JavaScript 现在开始日益重要起来,而且成为了广泛应用于 Web 开发的脚本语言。JavaScript 的复苏使一些业界领袖人物也不得不开始重新审视这种编程语言。诸如 Ajax (Asynchronous JavaScript + XML) 这样的编程技术让 Web 网页更加迷人。而完整的 Web 开发框架,比如 Apache Cocoon,则让 JavaScript 的应用越来越多,使其不只限于是一种用于制作 Web 页面的简单脚本。JavaScript 的一种称为 ActionScript 的派生物也推动了 Macromedia 的 Flash 客户端框架的发展。运行在 JVM 上的实现 Rhino 让 JavaScript 成为了 Java™ 开发人员所首选的一类脚本语言(参见 参考资料)。

    我的好友兼同事 Stuart Halloway 是 Ajax 方面的专家,曾在其教授的 JavaScript 课程中做过这样的开场白:“到 2011 年,JavaScript 将被公认为是一种拥有开发现代应用程序所需的一整套新特性的语言” 。他继而介绍说 JavaScript 程序要比类似的 Java 程序紧密十倍,并继续展示了使其之所以如此的一些语言特性。

    关于这个系列

    跨越边界系列中,作者 Bruce Tate 提出了这样一个主张:今天的 Java 程序员通过学习其他技术和语言,会得到很好的帮助。编程领域已经发生了变化,Java 技术不再是所有开发项目理所当然的最佳选择。其他框架正在影响 Java 框架构建的方式,而从其他语言学到的概念也有助于 Java 编程。对 Python(或 Ruby、Smalltalk 等等)代码的编写可能改变 Java 编码的方式。

    这个系列介绍的编程概念和技术,与 Java 开发有根本的不同,但可以直接应用于 Java 编程。在某些情况下,需要集成这些技术来利用它们。在其他情况下,可以直接应用这些概念。单独的工具并不重要,重要的是其他语言和框架可以影响 Java 社区中的开发人员、框架,甚至是基本方式。

    在这篇文章中,我将带您探究 JavaScript 的一些特性,看看这些特性如何让它如此具有吸引力:

    • 高阶函数: 一个高阶函数可以将函数作为参数,也可以返回一个函数。此特性让 JavaScript 程序员可以用 Java 语言所不能提供的方法来操纵函数。

    • 动态类型:通过延迟绑定,JavaScript 可以更准确和更灵活。

    • 灵活的对象模型:JavaScript 的对象模型使用一种相对不常见的方式进行继承 —— 称为原型 —— 而不是 Java 语言中更常见的基于类的对象模型。

    您可能已经熟悉动态类型模型、高阶函数形式的函数式编程以及开放对象模型这些概念,因为我在其他的跨越边界 系列文章中已经作过相关的介绍。如果您从未进行过任何正式的 JavaScript 开发,您很可能会认为这些特性属于非常复杂的语言,例如 Python、Lisp、Smalltalk 和 Haskell,而绝非像 JavaScript 这样的语言所能提供的。因此,我将用实际的代码示例来说明这些概念。

    立即开始

    您无需设置 JavaScript。如果您可以在浏览器中阅读此篇文章,就证明您已经准备就绪了。本文包含的所有编程示例都可以在大多数浏览器内运行。我使用的是 Firefox。

    用在 <script type='text/javascript'></script> 标记之间所包含的 JavaScript 加载简单的 Web 页面。清单 1 可以显示 Hello, World 文本:



    清单 1. Hello, world
    				
    <script type='text/javascript'>
    alert('Hello, World.')
    </script>
    

    要运行此代码,只需创建一个名为 example1.html 的文件。将清单 1 的代码复制到该文件内,并在浏览器中加载此文件(参看 下载 部分以获得本文使用的所有示例 HTML 文件)。注意到每次重载此页面时,该代码都会立即执行。

    alert 是个函数调用,只有一个字符串作为参数。图 1 显示了由清单 1 中的代码弹出的警告框,显示文本 “Hello, World”。如果代码在 HTML body 之内(目前并未指定任何 body,但浏览器能接受不规则的 HTML,并且整个页面都默然作为一个 body 被处理)。页面一旦加载,JavaScript 就会立即执行。



    图 1. Hello, world
    Hello, World.

    如果要延迟执行,可以在 HTML <head> 元素声明 JavaScript 函数,如清单 2 所示:



    清单 2. 延迟执行
    				
    <head>
        
        <script type='text/javascript'>
            function hello() {
                alert('Hello, World.')
            }
        </script>
    </head>
    <body>
        <button onclick="hello();">Say Hello</button>
    </body>
    

    将清单 2 中的代码输入到一个 HTML 文件,在浏览器内加载该文件,单击 Say Hello 按钮,结果如图 2 所示:



    图 2. 延迟执行
    延迟执行




    回页首


    高阶函数

    清单 2,可以大致体会到一些 JavaScript 在操纵函数方面的能力。将函数名称传递给 HTML button 标记并利用 HTML 的内置事件模型。使用 JavaScript 时,我会经常在变量或数组中存储函数(在本文后面的 对象模型 一节,您会看到 JavaScript 对象模型策略大量使用了此技巧)。例如,查看一下清单 3:



    清单 3. 用变量操纵函数
    				
    <head>
        
        <script type='text/javascript'>
            hot = function hot() {
                alert('Sweat.')
            }
            cold  = function cold() {
                alert('Shiver.')
            }
            
            function swap() {
                temp = hot
                hot = cold
                cold = temp    
                alert('Swapped.')
            }
        </script>
    </head>
    <body>
        <button onclick="hot();">Hot</button>
        <button onclick="cold();">Cold</button>
        <button onclick="swap();">Swap</button>
    </body>
    

    函数是 JavaScript 中的一类对象,可以自由地操纵它们。首先我声明两个函数:hotcold。并分别在不同的变量存储它们。单击 Hot 或 Cold 按钮会调用对应的函数,生成一个告警。接下来,声明另一个函数用来交换 Hot 和 Cold 按钮的值,将此函数与第三个按钮关联,该按钮显示如图 3 所示的告警:



    图 3. 操纵函数

    这个例子说明可以像处理其他变量一样处理函数。C 开发人员很容易将此概念看作是函数指针 功能,但 JavaScript 的高阶函数的功能更为强大。该特性让 JavaScript 程序员能够像处理其他变量类型一样轻松处理动作或函数。

    将函数用作函数的参数,或将函数作为值返回,这些概念属于高阶函数的领域。清单 4 对 清单 3 做了一点点修改,显示了能返回函数的高阶函数:



    清单 4. 高阶函数
    				
    <head>
    
        <script type='text/javascript'>
    
            function temperature() {
                return current
            }
    
            hot = function hot() {
                alert('Hot.')
            }
    
            cold  = function cold() {
                alert('Cold.')
            }
    
            current = hot
    
            function swap() {
                if(current == hot) {
                  current = cold
                } else {
                  current = hot
                }
            }
        </script>
    </head>
    <body>
        <button onclick="funct = temperature()();">Temperature</button>
        <button onclick="swap();">Swap</button>
    </body>
    

    这个例子解决了一个常见问题:如何将更改中的行为附加到用户接口事件?通过高阶函数,这很容易做到。temperature 高阶函数返回 current 的值,而 current 又可以有 hotcold 函数。看一下这个有些陈旧的函数调用:temperature()()。第一组括号用于调用 temperature 函数。第二组括号调用由 temperature返回 的函数。图 4 显示了输出:



    图 4. 高阶函数
    高阶函数

    高阶函数是函数式编程的基础,对比面向对象编程,函数式编程代表了更高级别的抽象。但 JavaScript 的实力并不仅限于高阶函数。JavaScript 的动态类型就极为适合 UI 开发。





    回页首


    动态类型

    通过静态类型,编译器可以检查参数和变量的值或针对一个给定操作所允许的返回值。其优势是编译器可以做额外的错误检查。而且静态类型还可以为诸如 IDE 这样的工具提供更多信息,带来其他一些特性,比如更好的代码完成功能。但静态类型也存在着如下一些劣势:

    • 必须提前声明意图,这常常会导致灵活性降低。例如,更改一个 Java 类就会更改类的类型,因而必须重新编译。对比之下,Ruby 允许开放的类,但更改一个 Java 类还是会更改类的类型。

    • 要实现相同的功能,必须输入更多的代码。例如,必须用参数形式包括进类型信息,必须用函数形式返回值和所有变量的类型。另外,还必须声明所有变量并显式地转化类型。

    • 静态语言的编译-部署周期要比动态语言的部署周期长,尽管一些工具可被用来在某种程度上缓解这一问题。

    静态类型更适合用于构建中间件或操作系统的语言中。UI 开发常常需要更高的效率和灵活性,所以更适合采用动态类型。我深知这种做法存在危险。相信使用过 JavaScript 的 Web 开发人员都曾经为编译器本应检测到的错误类型的变量而绞尽脑汁。但它所带来的优势同样不可否认。下面将举例加以说明。

    首先,考虑一个对象的情况。在清单 5 中,创建一个新对象,并访问一个不存在的属性,名为 color



    清单 5. 引入一个属性
    				
    <script type='text/javascript'>
        blank_object = new Object();
        blank_object.color = 'blue'
        alert('The color is ' + blank_object.color)
    </script>
    

    当加载并执行此应用程序时,会得到如图 5 所示的结果:



    图 5. 引入属性
     引入属性

    JavaScript 并不会报告 blue 属性不存在的错误。静态类型的拥护者大都会被本例所吓倒,因为本例中的错误被很好地隐匿了。虽然这种做法多少会让您感觉有些不正当,但您也不能否认它巨大的诱惑力。您可以很快引入属性。如果将本例和本文之前的例子结合起来,还可以引入行为。记住,变量可以保存函数!所以,基于动态类型和高阶函数,您可以在任何时候向类中引入任意的行为。

    可以轻松地重写 清单 5,使其如清单 6 所示:



    清单 6. 引入行为
    				
    <script type='text/javascript'>
        blank_object = new Object();
        blank_object.color = function() { return 'blue'}
        alert('The color is ' + blank_object.color())
    </script>
    

    从上例可以看出,在 JavaScript 的不同概念之间可以如此轻松地来回变换,其含义上的变化很大 —— 比如,是引入行为还是引入数据 —— 但语法上的变化却很小。该语言很好的延展性是它的一种优势,但同样也是其缺点所在。实际上,该语言本身的对象模型就是 JavaScript 延展程度的一种体现。





    回页首


    对象模型

    到目前为止,您应该对 JavaScript 有一个正确的评价了,它绝非只如一个玩具那么简单。事实上,很多人都使用过其对象模型创建过极为复杂、设计良好的面向对象软件。但对象模型尤其是用于继承的对象模型又非您一贯认为的那样。

    Java 语言是基于类的。当构建应用程序时,也同时构建了可以作为所有对象的模板的新类。然后调用 new 来实例化该模板,创建一个新对象。而在 JavaScript 中,所创建的是一个原型,此原型是一个实例,可以创建所有未来的对象。

    现在先暂且放下这些抽象的概念,去查看一些实际代码。比如,清单 7 创建了一个简单的 Animal,它具有 name 属性和 speak 动作。其他动物会从这个基础继承。



    清单 7. 创建一个构造函数
    				
    <script type='text/javascript'>        
    Animal = function() {
        this.name = "nobody"
        this.speak = function () {
            return "Who am I?"
        }
    }
    
    myAnimal = new Animal();
    alert('The animal named ' + myAnimal.name + 
          ' says ' + myAnimal.speak());
    
    </script>
    

    清单 7 的结果如图 6 所示:



    图 6. 创建一个构造函数
    构造函数

    对于 Java 开发人员而言,清单 7 中的代码看起来多少有点生疏和奇怪。实际上对于没有亲自构建过对象的许多 JavaScript 开发人员来说,这些代码同样看起来有点生疏和奇怪。也许,下面的解释可以让大家能够更好地理解这段代码。

    实际上,您只需重点关注其中三段信息。首先,JavaScript 用嵌套函数表示对象。这意味着清单 7 中的 Animal 的定义是一种有效的语法。第二,JavaScript 基于原型或现有的对象的实例来构造对象,而非基于类模板。funct() 是一种调用,但 new Animal() 却基于 Animal 内的原型构造一个对象。最后,在 JavaScript 中,对象只是函数和变量的集合。每个对象并不与类型相关,所以可以自由地修改这种结构。

    回到 清单 7。如您所见,JavaScript 基于在 Animal 中指定的原型定义一个新对象:myAnimal。继而可以使用原型中的属性和函数,甚或重定义函数和属性。这种灵活性可能会让 Java 开发人员受不了,因为他们不习惯这种行为,但它的确是一种十分强大的模型。

    现在我还要更深入一步。您还可以使用名为 prototype 实例变量来指定对象的基础。方法是设置 prototype 实例变量使其指向继承链的父。如此设置 prototype 之后,您所创建的对象会为未指定的那些对象继承属性和函数。这样一来,您就可以模仿面向对象的继承概念。以清单 8 为例:



    清单 8. 通过原型继承
    				
    <script type='text/javascript'>        
    
    Animal = function() {
        this.name = "nobody"
        this.speak = function () {
            return "Who am I?"
        }
    }
    Dog = function() {
      this.speak = function() {
        return "Woof!"
      }
    }
    Dog.prototype = new Animal();
    
    myAnimal = new Dog();
    alert('The animal named ' + myAnimal.name + 
          ' says ' + myAnimal.speak());
          </script>
    

    在清单 8 中,创建了一个 Dog 原型。此原型基于 AnimalDog 重定义 speak() 方法但却不会对 name() 方法做任何改动。随后,将原型 Dog 设置成 Animal。图 7 显示了其结果:



    图 7. 通过原型继承
    继承

    这也展示了 JavaScript 是如何解决到属性或方法的引用问题的:

    • JavaScript 基于原始的原型创建实例,该原型在构造函数中定义。任何对方法或属性的引用都会使用所生成的原始副本。

    • 您可以在对象内像定义其他任何变量一样重新定义这些变量。这样做必然会更改此对象。所以您显式定义的任何属性或函数都将比在原始的原型中定义的那些属性或函数优先级要高。

    • 如果您显式设置了名为 prototype 的实例变量,JavaScript 就会在此实例中寻找任何未定义的实例变量或属性。这种查找是递归的:如果 在 prototype 内定义的实例不能找到属性或函数,它就会在 原型中查找,依此类推。

    那么,JavaScript 的继承模型到底是什么样的?这取决于您如何对它进行定义。您需要定义继承行为以便可以覆盖它。然而,从本质上讲,JavaScript 更像是一种函数式语言,而非面向对象的语言,它使用一些智能的语法和语义来仿真高度复杂的行为。其对象模型极为灵活、开放和强大,具有全部的反射性。有些人可能会说它太过灵活。而我的忠告则是,按具体作业的需要选择合适的工具。





    回页首


    结束语

    JavaScript 对象模型构建在该语言的其他功能之上来支持大量的库,比如 Dojo(参见 参考资料)。这种灵活性让每个框架能够以一种精细的方式更改对象模型。在某种程度上,这种灵活性是一种极大的缺点。它可以导致可怕的互操作性问题(尽管该语言的灵活性可以部分缓解这些问题)。

    而另一方面,灵活性又是一种巨大的优势。Java 语言一直苦于无法充分增强其灵活性,原因是它的基本对象模型还未灵活到可以被扩展的程度。一个典型的企业级开发人员为能够成功使用 Java 语言必须要学习很多东西,而新出现的一些优秀的开放源码项目和新技术,比如面向方面编程、Spring 编程框架和字节码增强库,则带来了大量要学的代码。

    最后,JavaScript 优秀的灵活性的确让您体会到了一些高阶语言的强大功能。当然您无需选择为每个项目或大多数项目都做这样的权衡和折衷。但了解一种语言的优势和劣势 —— 通过参考大量信息,而不仅仅基于广告宣传或公众意见 —— 会让您可以更好地控制何时需要使用以及何时不能使用这种语言。当您在修改 JavaScript Web 小部件时,您至少知道该如何让此语言发挥它最大的优势。请继续跨越边界吧。


    参考资料

    学习
    posted @ 2007-01-21 15:49 海思 阅读(228) | 评论 (0)编辑 收藏

    1、取出刚刚插入(删除)的数据SELECT 字段名 FROM INSERTED(DELETED)
    2、对于UPDATE实际上是先DELETE然后再INSERT所以如果想得到UPDATE前后的数据值,应该先从DELETED取出,然后从INSERTED取出;
    3、IF UPDATE(列名)可以判断更新或插入哪一个字段的值;
    4、@@ROWCOUNT可以判断上一行查询操作得到的列数;
    5、给变量赋值用SET @ZQB = 13;
    6、察看是否有符合条件的记录IF EXISTS (SELECT name FROM sysobjects WHERE name = 'reminder' AND type = 'TR');
    7、定义游标,如下:
    DECLARE c1 CURSOR FOR
    SELECT emp_mgr.emp
    FROM emp_mgr, inserted
    WHERE emp_mgr.emp = inserted.mgr

    OPEN c1
    FETCH NEXT FROM c1 INTO @e--从游标中取出数据
    WHILE @@fetch_status = 0--判断是否到最后
    BEGIN
    UPDATE emp_mgr
    SET emp_mgr.NoOfReports = emp_mgr.NoOfReports + 1 -- Add 1 for newly
    WHERE emp_mgr.emp = @e -- added employee.

    FETCH NEXT FROM c1 INTO @e
    END
    CLOSE c1
    DEALLOCATE c1--删除游标引用

    posted @ 2007-01-07 14:34 海思 阅读(207) | 评论 (0)编辑 收藏