最爱Java

书山有路勤为径,学海无涯苦作舟

2009年10月20日

    Java程序的国际化主要通过三个类完成:

    java.util.ResourceBundle:用于加载一个资源包。

    java.util.Locale:对应一个特定的国家/区域、语言环境。

    java.text.MessageFormat:用于消息格式化。

    而资源文件的命名方式主要有三种:baseName_language_country.properties、baseName_language.properties和baseName.properties。

    以下的程序可以得到Java所支持的语言和国家:

public class LocalList {
    
public static void main(String[] args){
        Locale[] localeList 
= Locale.getAvailableLocales();
        
for (int i=0;i<localeList.length;i++){
            System.out.println(localeList[i].getdisplayCountry() 
+ "=" + localeList[i].getCountry() + " " + localeList[i].getDisplayLanguage() + "=" + localeList[i].getLanguage());
        }

    }

}

    使用国际化的代码如: 

public class Hello{
    
public static void main(String[] args){
        Locale myLocale 
= Locale.getDefault();
        ResourceBundle bundle 
= ResourceBundle.getBundle("mess",myLocale);
        System.out.println(bundler.getString(
"hello"));
    }

}

    如果在资源文件中,存在例如msg = Hello,{0}!Today is {1}.这样需要程序动态插入参数的文本,则需要使用MessageFormat类的format()方法。

    除了使用资源文件,我们也可以使用类文件来代替资源文件。使用Java文件代替资源文件的Java文件必须满足:1。类名必须是baseName_language_country,这与属性文件的命名相似。2。该类必须继承ListResourceBundle,并重写getContents方法,该方法返回Object数组。该数组的每一个项都是key-value对。

public class MyResource_zh_CN extends ListResourceBundle {
    
//定义资源
    private final Object myData[][] = {
        
{"msg","类文件消息:{0},您好!今天是{1}"}
    }
;
    @Override
    
public Object[][] getContents(){
        
return myData;
    }

}


    对于简体中文的Locale,ResourceBundler搜索资源的顺序是:

    baseName_zh_CN.class;baseName_zh_CH.properties;baseName_zh.class;baseName_zh.properties;baseName.class;baseName.properties

 

    Struts2访问国际化消息,主要有3种方式:1)JSP页面输出国际化消息,可以使用Struts2的<s:text.../>标签,该标签可以指定一个name属性,该属性就是资源文件中的key。2)在Action中,可以使用ActionSupport类的getText方法,该方法可以接受一个name参数,指定了国际化资源文件中的key。3)表单元素的Label,可以为表单标签指定一个key属性,这个key指定了国际化资源文件的key。

     对于带占位符的国际化消息,在Action中,则需要使用getText(String key, String[] args)来处理,其中args就是参数列表;而在页面中,则需要为<s:text.../>标签指定<s:param.../>子标签。如:

<s:text name="welcomeMsg">
    
<s:param><s:property value="username"></s:param>
</s:text>


   在Struts2中,还有一种更加简单的表达方式。我们可以在资源文件中写例如这样的表达式:failTip=${username},对不起,您不能登录!,通过使用表达式,可以从ValueStack中取出username属性值,自动填充到消息资源中。这在Action中很常用。

    对于一个大型应用而言,国际化资源文件的管理也是一个非常浩大的工程。为了能更好的分而治之,Struts2允许针对不同的模块、不同Action来组织国家化资源文件。

     为Strut2应用指定包范围资源文件的方法是:在包的跟路径下建立多个文件名为package_language_country.properties的文件,一旦建立了这个系列的国际化资源文件,应用中处于该包下的所有Action都可以访问该资源文件。

    例如一个Action为codes\packageScope\src\lee\action\LoginAction.java,那么我们可以提供package_zh_CN.properties和package_en_US.properties两个文件放在codes\packageScope\src\lee目录下,那么这两个文件就能被lee包及lee包下所有子包内的Action所能访问。

    同时,我们也可以为LoginAction单独指定一份国际化资源文件。即在codes\packageScope\src\lee\action目录下,分别建立LoginAction_zh_CN.properties和LoginAction_en_US.properties两个文件。

    有时候,处于某种特殊的原因,我们需要临时指定资源文件,那么就需要使用<s:i18n.../>来充当<s:text.../>标签的父标签了。如:

<s:i18n name="tmp">
    
<s:text name="loginPage"/>
</s:i18n>

<s:i18n name="tmp">
    
<s:form action="login">
        
<s:textfield name="username" key="user"/>
        
<s:textfield name="password" key="pass"/>
        
<s:submit key="login"/>
    
</s:form>
</s:i18n>


    加载资源文件的顺序:

  1.     优先加载系统中保存在ChildAction的类文件相同位置,且baseName为ChildAction的系列资源文件。
  2.     如果在1)中找不到key对应的消息,且ChildAction有父类ParentAction,则加载系统中保存在ParentAction的类文件相同位置,且baseName为ParentAction的系列资源文件。
  3.     如果2)中找不到key对应的消息,且ChildAction有实现接口IChildAction,则加载系统中保存在IChildAction的类文件相同位置,且baseName为IChildAction的系列资源文件。
  4.     如果3)中找不到key对应的消息,且ChildAction有实现接口ModelDriven(即使用模型驱动模式),则对于getModel()方法返回的model对象,重新执行1)步操作。
  5.     如果在4)中找不到key对应的消息,则查找当前包下baseName为package的系列资源文件。
  6.     如果在5)中找不到key对应的消息,则沿着当前包上溯,直到最顶层包来查找baseName为package的系列资源文件。
  7.     如果在6)中找不到key对应的消息,则查找struts.custom.i18n.resources常量指定baseName的系列资源文件。
  8.     如果经过上面步骤一直找不到key对应的消息,将直接输出该key的字符串值

      对于在JSP中访问国际化消息,则简单很多,可以分为两种形式:

      1)对于使用<s:i18n.../>标签作为父标签的<s:text.../>标签,将直接从<s:i18n.../>标签指定的国际化资源文件中加载指定key对应的消息,如果没有,则读取struts.custom.i18n.resources常量指定baseName的系列文件。如果还没有,直接输出key。

     2)对于没有使用<s:i18n.../>标签作为父标签的<s:text.../>标签,则直接读取struts.custom.i18n.resources常量指定baseName的系列文件。如果没有,直接输出key。

    Struts2中, 我们可以通过ActionContext.getContext().setLocale(Locale arg)设置用户的默认语言。同时在Struts2 的defaultStack拦截栈中,i18n拦截器也能设置默认语言。i18n在执行Action方法前,会自动查找一个名为request_locale的参数。如果这个参数存在,则拦截器会将其转换成Locale对象,并设为默认的Locale。同时,这个Locale对象会保存在Session的名为WW_TRANS_I18N_LOCALE的属性中。一旦用户的Session中有WW_TRANS_I18N_LOCALE属性,则属性指定的Locale将会作为浏览器的默认Locale。因此,用户也可利用此功能来开发自行选择语言的功能。

posted @ 2010-11-11 22:16 Brian 阅读(311) | 评论 (0)编辑 收藏
     摘要:     Struts2默认使用Jakarta的Common-FileUpload的文件上传解析器。见struts.properties配置文件中: Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->#指定使用COS的文件上...  阅读全文
posted @ 2010-11-07 14:19 Brian 阅读(460) | 评论 (0)编辑 收藏

    对于login方法的校验,可以通过<ActionClassName>-<ActionAliasName>-validation.xml文件来校验,即RegistAction-login-validation.xml文件进行校验。同时,RegistAction-validation.xml的校验规则仍旧对login方法有效。即login方法的校验规则是Region-validation.xml和RegistAction-login-validation.xml的总和。
    如果RegistAction继承了BaseAction,那么对于BaseAction类的校验规则也会被RegistAction类所继承校验。具体来说,其校验规则的搜索文件规则如下:
        BaseAction-validation.xml
        BaseAction-别名-validation.xml
        RegistAction-validation.xml
        RegistAction-别名-validation.xml

    对于Struts2所支持的内建校验器,我们可以通过xwork.2.1.2.jar中的com/opensymphony/xwork2/validator/validators/default.xml文件查看。

    除了配置文件,Struts2也支持Annotation。下面就是使用Annotation配置的RegistAction:

@Validation()
public class RegistAction extends ActionSupport {
    private static final long serialVersionUID = -2113900523366315993L;
    
    //该请求包含的4个请求参数
    private String name;
    private String pass;
    private int age;
    private Date birth;
    
    
    public String getName() {
        return name;
    }
        @RequiredStringValidator(type=ValidatorType.FIELD,key="name.required",message="")
        @RegexFieldValidator(type=ValidatorType.FIELD,expression="\\w{4,25}",key="name.regex",message="")
    public void setName(String name) {
        this.name = name;
    }
    public String getPass() {
        return pass;
    }
        @RequiredStringValidator(type=ValidatorType.FIELD,key="pass.required",message="")
        @RegexFieldValidator(type=ValidatorType.FIELD,expression="\\w{4,25}",key="pass.regex",message="")
    public void setPass(String pass) {
        this.pass = pass;
    }
    public int getAge() {
        return age;
    }
        @IntRangeFieldValidator(message="",key="age.range",min="1",max="150")
    public void setAge(int age) {
        this.age = age;
    }
    public Date getBirth() {
        return birth;
    }
        @DateRangeFieldValidator(message="",key="birth.range",min="1900/01/01",max="2050/01/21")
    public void setBirth(Date birth) {
        this.birth = birth;
    }
}

     

    对于不能通过内置校验器进行校验的逻辑,则可通过重写validate()方法来实现。如果一个Action中存在多个逻辑处理,则需要通过validateXxx()方法来分别进行校验,其中Xxx代表方法名。如login()方法对应的校验方法为validateLogin()。

    Struts2的输入校验流程:

    1。类型转换器负责对字符串的请求参数执行类型转换,并将这些值设置成Action的属性值。

    2。在执行类型转换过程中,如果发生异常,则将异常保存到ActionContext中,并由conversionError拦截器负责将其封装到fieldError里。然后执行第3步;如无异常,直接执行第3步。

    3。调用Struts2内置的输入校验规则进行输入校验

    4。通过放射调用validateXxx()方法。

    5。调用validate()方法。

    6。如果上述都未发生fieldError,将调用Action里处理用户请求的处理方法;如果出现了fieldError,则转入input逻辑视图所指定的视图资源。

posted @ 2010-10-24 15:35 Brian 阅读(461) | 评论 (1)编辑 收藏
     摘要:     Struts2提供了基于验证框架的输入校验,在这种校验方式下,所有的输入校验只需要通过指定的配置文件即可。Struts2中每个Action都有一个校验文件,其规则为:<Action名字>-validation.xml。如: Code highlighting produced by Actipro CodeHighlighter (freewar...  阅读全文
posted @ 2010-10-24 15:01 Brian 阅读(334) | 评论 (0)编辑 收藏
     摘要: Ext.data.Connection     Ext.data.Connection是对Ext.lib.Ajax的封装,它提供了配置使用Ajax的通用方式,它在内部通过Ext.lib.Ajax实现与后台的异步调用。与底层的Ext.lib.Ajax相比,Ext.data.Connection提供了更简洁的配置方式,使用起来更方便。   ...  阅读全文
posted @ 2009-10-27 11:00 Brian 阅读(1373) | 评论 (1)编辑 收藏
     摘要: 简单菜单 //创建工具条 var tb = new Ext.Toolbar(); tb.render('toolbar'); //为工具条添加按钮 tb.add({     text:'新建',     //对应的事件处理函数   ...  阅读全文
posted @ 2009-10-26 14:43 Brian 阅读(2022) | 评论 (0)编辑 收藏
     摘要: 布局概述              在EXT中,所有的布局都是从Ext.Container开始的,Ext.Container的父类是Ext.BoxComponent。Ext.BoxComponent是一个盒子组件,可以定义宽度,高度和位置等属性。作为子类,Ext.Co...  阅读全文
posted @ 2009-10-26 12:23 Brian 阅读(2805) | 评论 (0)编辑 收藏
Ext.MessageBox

 1//Ext.MessageBox.alert()
 2Ext.MessageBox.alert('标题','内容',function(btn){
 3    alert('你刚刚点击了' + btn);
 4}
);
 5
 6//Ext.MessageBox.confirm()
 7Ext.MessageBox.confirm('选择框','你到底是选择Yes还是No?', function(btn) {
 8    alert('你刚刚点击了' + btn);
 9}
);
10
11//Ext.MessageBox.prompt()
12Ext.MessageBox.prompt('输入框','随便输入一些东西', function(btn,text) {
13    alert('你刚刚点击了' + btn + ", 刚刚输入了" + text);
14}
);
    
对话框的更多配置

 1//可以输入多行的输入框
 2Ext.MessageBox.show({
 3    title:'多行输入框',
 4    msg:'你可以多输入好几行',
 5    width:300,
 6    buttons:Ext.MessageBox.OKCANCEL,
 7    multiline:true,
 8    fn:function(btn,text){
 9        alert('你刚刚点击了' + btn + ", 刚刚输入了" + text);
10    }

11}
);
12
13//自定义对话框的按钮
14Ext.MessageBox.show({
15    title:'随便按个按钮',
16    msg:'从三个按钮里随便选择一个',
17    buttons:Ext.MessageBox.YESNOCANCEL,
18    multiline:true,
19    fn:function(btn){
20        alert('你刚刚点击了' + btn);
21    }

22}
);

    Ext.MessageBox中预设的4个按钮分别是OK,Yes,No,Cancel。如果不使用YESNOCANCEL这种预设变量,也可以直接使用{ok:true, yes:true, no:true,cancel:true}的形式,这样4个按钮都会显示在对话框中。

进度条

 1Ext.MessageBox.show({
 2    title:'请等待',
 3    msg:'读取数据中',
 4    width:240,
 5    progress:true,
 6    closable:false  //隐藏对话框右上角的关闭按钮,从而禁止用户关闭进度条
 7}
);
 8
 9//也可以直接使用Ext.MessageBox.progress()
10Ext.MessageBox.progress('请等待',msg:'读取数据中');
11

    上述的进度状态时不会发生变化的,我们需要调用Ext.MessageBox.updateProgress()函数,如以下为每秒变化,10秒后隐藏:

 1var f = function(v){
 2    return function(){
 3        if (v == 11{
 4            Ext.MessageBox.hide();
 5        }
 esle {
 6            Ext.MessageBox.updateProgress(v/10,'正在读取第' + v + '个,一共10个');
 7        }

 8    }
;
 9}
;
10for (var i = 1 ; i < 12 ; i++{
11    setTimeout(f(i) , i*1000);
12}

    还可以使用一种自动变化的进度条提示框,如Ext.MessageBox.wait('请等待', msg: ' 读取数据中');

动画效果
    
可以为对话框这是弹出和关闭的动画效果,使用animEl参数指定一个HTML元素,对话框就会依据指定的HTML元素播放弹出和关闭的动画。

窗口分组

 1        <script type="text/javascript">
 2var i = 0 , mygroup;
 3
 4function newWin(){
 5    var win = new Ext.Window({
 6        title:'窗口'+ i++,
 7        width:400,
 8        height:300,
 9        maximizable:true,
10        manager:mygroup
11    }
);
12    win.show();
13}

14
15function toBack(){
16    mygroup.sendToBack(mygroup.getActive());
17}

18
19function hideAll(){
20    mygroup.hideAll();
21}

22
23Ext.onReady(function(){
24    mygroup = new Ext.WindowGroup();
25
26    Ext.get("btn").on("click",newWin);
27    Ext.get("btnToBack").on("click",toBack);
28    Ext.get("btnHide").on("click",hideAll);
29}
);
30        </script>
31
32 <BODY>
33    <input id="btn" type="button" name="add" value="新窗口"/>
34    <input id="btnToBack" type="button" name="btnToBack" value="放到后台"/>
35    <input id="btnHide" type="button" name="btnHide" value="隐藏所有"/>
36 </BODY>

    示例中,所有通过newWind()方法产生的窗口都属于mygroup窗口组
posted @ 2009-10-25 11:24 Brian 阅读(5554) | 评论 (2)编辑 收藏
     摘要: 先看最简单的拖放: 1new Ext.dd.DDProxy('block'); 2//对应的HTML部分代码 3<div id="block" style="background:red;">&nbsp;</div>  拖放组件的体系     简单来说,左面4个组件都是...  阅读全文
posted @ 2009-10-23 23:42 Brian 阅读(3090) | 评论 (0)编辑 收藏
     摘要: 基本输入控件Ext.form.Field     Ext.form.Field是所有表单输入控件的基类,其他的输入控件都是基于它扩展的来的。其定义了输入控件通用的属性和功能函数,这些通用的属性和功能函数大致分为3大类:页面显示样式、控件参数配置和数据有效性校验。     页面显示样式:clearCls, cls, ...  阅读全文
posted @ 2009-10-22 14:31 Brian 阅读(2945) | 评论 (0)编辑 收藏
     摘要: 制作一个简单的Grid  1var cm = new Ext.grid.ColumnModel([  2    {header:'编号',dataIndex:'id'},  3    {header:'名称',dataIndex:'name...  阅读全文
posted @ 2009-10-21 15:05 Brian 阅读(4746) | 评论 (2)编辑 收藏
     摘要:         本文转载于javaeye(http://www.javaeye.com/wiki/Object_Oriented_JavaScript/1279-javascript-object-oriented-technology-one),只进行了重新排版以便收藏。    &nb...  阅读全文
posted @ 2009-10-20 11:47 Brian 阅读(256) | 评论 (0)编辑 收藏
        本文转载于javaeye(http://www.javaeye.com/wiki/Object_Oriented_JavaScript/1279-javascript-object-oriented-technology-one),只进行了重新排版以便收藏。
        文中所有英文语句(程序语句除外),都引自<<javascript-the definitive guide,5th edition>>。

------------------------------------------------------------------------------------
类变量/类方法/实例变量/实例方法
        先补充一下以前写过的方法:
        在javascript中,所有的方法都有一个call方法和apply方法。这两个方法可以模拟对象调用方法。它的第一个参数是对象,后面的参数表示对象调用这个方法时的参数(ECMAScript specifies two methods that are defined for all functions, call() and apply(). These methods allow you to invoke a function as if it were a method of some other object. The first argument to both call() and apply() is the object on which the function is to be invoked; this argument becomes the value of the this keyword within the body of the function. Any remaining arguments to call() are the values that are passed to the function that is invoked)。比如我们定义了一个方法f(),然后调用下面的语句:
    f.call(o, 1, 2);
作用就相当于
    o.m = f;
    o.m(1,2);
    delete o.m;
举个例子:
 1function Person(name,age) {  //定义方法   
 2    this.name = name;   
 3    this.age = age;   
 4}
   
 5var o = new Object();   //空对象   
 6alert(o.name + "_" + o.age); //undefined_undefined   
 7  
 8Person.call(o,"sdcyst",18); //相当于调用:o.Person("sdcyst",18)   
 9alert(o.name + "_" + o.age); //sdcyst_18   
10  
11Person.apply(o,["name",89]);//apply方法作用同call,不同之处在于传递参数的形式是用数组来传递   
12alert(o.name + "_" + o.age); //name_89  

---------------------------------

实例变量和实例方法都是通过实例对象加"."操作符然后跟上属性名或方法名来访问的,但是我们也可以为类来设置方法或变量,
这样就可以直接用类名加"."操作符然后跟上属性名或方法名来访问。定义类属性和类方法很简单:

 1Person.counter = 0;   //定义类变量,创建的Person实例的个数
 2function Person(name,age) {
 3    this.name = name;
 4    this.age = age;
 5    Person.counter++//没创建一个实例,类变量counter加1
 6}
;
 7
 8Person.whoIsOlder = function(p1,p2) //类方法,判断谁的年龄较大
 9    if(p1.age > p2.age) {
10        return p1;
11    }
 else {
12        return p2;
13    }

14}

15
16var p1 = new Person("p1",18);
17var p2 = new Person("p2",22);
18
19alert("现在有 " + Person.counter + "个人");  //现在有2个人
20var p = Person.whoIsOlder(p1,p2);
21alert(p.name + "的年龄较大");   //p2的年龄较大

prototype属性的应用:
下面这个例子是根据原书改过来的.
假设我们定义了一个Circle类,有一个radius属性和area方法,实现如下:

1function Circle(radius) {
2    this.radius = radius;
3    this.area = function() {
4        return 3.14 * this.radius * this.radius;
5    }

6}

7var c = new Circle(1);
8alert(c.area());  //3.14

     假设我们定义了100个Circle类的实例对象,那么每个实例对象都有一个radius属性和area方法。实际上,除了radius属性,每个Circle类的实例对象的area方法都是一样,这样的话,我们就可以把area方法抽出来定义在Circle类的prototype属性中,这样所有的实例对象就可以调用这个方法,从而节省空间。

1function Circle(radius) {
2    this.radius = radius;
3}

4Circle.prototype.area = function() {
5        return 3.14 * this.radius * this.radius;
6    }

7var c = new Circle(1);
8alert(c.area());  //3.14

现在,让我们用prototype属性来模拟一下类的继承:首先定义一个Circle类作为父类,然后定义子类PositionCircle。

 1function Circle(radius) {  //定义父类Circle
 2    this.radius = radius;
 3}

 4Circle.prototype.area = function() //定义父类的方法area计算面积
 5    return this.radius * this.radius * 3.14;
 6}

 7
 8function PositionCircle(x,y,radius) //定义类PositionCircle
 9    this.x = x;                    //属性横坐标
10    this.y = y;                       //属性纵坐标
11    Circle.call(this,radius);      //调用父类的方法,相当于调用this.Circle(radius),设置PositionCircle类的
12                                   //radius属性
13}

14PositionCircle.prototype = new Circle(); //设置PositionCircle的父类为Circle类
15
16var pc = new PositionCircle(1,2,1);
17alert(pc.area());  //3.14
18                   //PositionCircle类的area方法继承自Circle类,而Circle类的
19                   //area方法又继承自它的prototype属性对应的prototype对象
20alert(pc.radius); //1  PositionCircle类的radius属性继承自Circle类
21
22/*
23注意:在前面我们设置PositionCircle类的prototype属性指向了一个Circle对象,
24因此pc的prototype属性继承了Circle对象的prototype属性,而Circle对象的constructor属
25性(即Circle对象对应的prototype对象的constructor属性)是指向Circle的,所以此处弹出
26的是Circ.
27*/

28alert(pc.constructor); //Circle    
29
30/*为此,我们在设计好了类的继承关系后,还要设置子类的constructor属性,否则它会指向父类
31的constructor属性
32*/

33PositionCircle.prototype.constructor = PositionCircle
34alert(pc.constructor);  //PositionCircle

posted @ 2009-10-20 11:34 Brian 阅读(206) | 评论 (0)编辑 收藏
        本文转载于javaeye(http://www.javaeye.com/wiki/Object_Oriented_JavaScript/1279-javascript-object-oriented-technology-one),只进行了重新排版以便收藏。
        文中所有英文语句(程序语句除外),都引自<<javascript-the definitive guide,5th edition>>。

------------------------------------------------------------------------------------
类、构造函数、原型

        先来说明一点:在上面的内容中提到,每一个函数都包含了一个prototype属性,这个属性指向了一个prototype对象(Every function has a prototype property that refers to a predefined prototype object  --section8.6.2)。注意不要搞混了。

构造函数:
        new操作符用来生成一个新的对象。new后面必须要跟上一个函数,也就是我们常说的构造函数。构造函数的工作原理又是怎样的呢?先看一个例子:
1function Person(name,sex) {   
2    this.name = name;   
3    this.sex = sex;   
4}
   
5var per = new Person("sdcyst","male");   
6alert("name:"+per.name+"_sex:"+per.sex); //name:sdcyst_sex:male  

        下面说明一下这个工作的步骤:
        开始创建了一个函数(不是方法,只是一个普通的函数),注意用到了this关键字。以前我们提到过this关键字表示调用该方法的对象,也就是说通过对象调用"方法"的时候,this关键字会指向该对象(不使用对象直接调用该函数则this指向整个的script域,或者函数所在的域,在此我们不做详细的讨论)。当我们使用new操作符时,javascript会先创建一个空的对象,然后这个对象被new后面的方法(函数)的this关键字引用!然后在方法中通过操作this,就给这个新创建的对象相应的赋予了属性。最后返回这个经过处理的对象。这样上面的例子就很清楚:先创建一个空对象,然后调用Person方法对其进行赋值,最后返回该对象,我们就得到了一个per对象。

        prototype(原型)--在这里会反复提到"原型对象"和"原型属性",注意区分这两个概念。
        在javascript中,每个对象都有一个prototype属性,这个属性指向了一个prototype对象。上面我们提到了用new来创建一个对象的过程,事实上在这个过程中,当创建了空对象后,new会接着操作刚生成的这个对象的prototype属性。每个方法都有一个prototype属性(因为方法本身也是对象),new操作符生成的新对象的prototype属性值和构造方法的prototype属性值是一致的。构造方法的prototype属性指向了一个prototype对象,这个prototype对象初始只有一个属性constructor,而这个constructor属性又指向了prototype属性所在的方法(In the previous section, I showed that the new operator creates a new, empty object and then invokes a constructor function as a method of that object. This is not the complete story, however. After creating the empty object, new sets the prototype of that object. The prototype of an object is the value of the prototype property of its constructor function. All functions have a prototype property that is automatically created and initialized when the function is defined. The initial value of the prototype property is an object with a single property. This property is named constructor and refers back to the constructor function with which the prototype is associated. this is why every object has a constructor property. Any properties you add to this prototype object will appear to be properties of objects initialized by the constructor. -----section9.2)

        有点晕,看下面的图:

        这样,当用构造函数创建一个新的对象时,它会获取构造函数的prototype属性所指向的prototype对象的所有属性。对构造函数对应的prototype对象所做的任何操作都会反应到它所生成的对象身上,所有的这些对象共享构造函数对应的prototype对象的属性(包括方法)。看个具体的例子吧:
 1function Person(name,sex) {  //构造函数   
 2    this.name = name;   
 3    this.sex = sex;   
 4}
   
 5Person.prototype.age = 12;   //为prototype属性对应的prototype对象的属性赋值   
 6Person.prototype.print = function() //添加方法   
 7    alert(this.name+"_"+this.sex+"_"+this.age);   
 8}
;   
 9  
10var p1 = new Person("name1","male");   
11var p2 = new Person("name2","male");   
12p1.print();  //name1_male_12   
13p2.print();  //name2_male_12   
14  
15Person.prototype.age = 18;  //改变prototype对象的属性值,注意是操作构造函数的prototype属性   
16p1.print();  //name1_male_18   
17p2.print();  //name2_male_18  

到目前为止,我们已经模拟出了简单的类的实现,我们有了构造函数,有了类属性,有了类方法,可以创建"实例"。在下面的文章中,我们就用"类"这个名字来代替构造方法,但是,这仅仅是模拟,并不是真正的面向对象的"类"。在下一步的介绍之前,我们先来看看改变对象的prototype属性和设置prototype属性的注意事项:给出一种不是很恰当的解释,或许有助于我们理解:当我们new了一个对象之后,这个对象就会获得构造函数的prototype属性(包括函数和变量),可以认为是构造函数(类)继承了它的prototype属性对应的prototype对象的函数和变量,也就是说,
prototype对象模拟了一个超类的效果。听着比较拗口,我们直接看个实例吧:

 1function Person(name,sex) {  //Person类的构造函数   
 2    this.name = name;   
 3    this.sex = sex;   
 4}
   
 5Person.prototype.age = 12;   //为Person类的prototype属性对应的prototype对象的属性赋值,   
 6                             //相当于为Person类的父类添加属性   
 7Person.prototype.print = function() //为Person类的父类添加方法   
 8    alert(this.name+"_"+this.sex+"_"+this.age);   
 9}
;   
10  
11var p1 = new Person("name1","male"); //p1的age属性继承子Person类的父类(即prototype对象)   
12var p2 = new Person("name2","male");   
13  
14p1.print();  //name1_male_12   
15p2.print();  //name2_male_12   
16  
17p1.age = 34//改变p1实例的age属性   
18p1.print();  //name1_male_34   
19p2.print();  //name2_male_12   
20  
21Person.prototype.age = 22;  //改变Person类的超类的age属性   
22p1.print();  //name1_male_34(p1的age属性并没有随着prototype属性的改变而改变)   
23p2.print();  //name2_male_22(p2的age属性发生了改变)   
24  
25p1.print = function() {  //改变p1对象的print方法   
26    alert("i am p1");   
27}
   
28  
29p1.print();  //i am p1(p1的方法发生了改变)   
30p2.print();  //name2_male_22(p2的方法并没有改变)   
31  
32Person.prototype.print = function() //改变Person超类的print方法   
33    alert("new print method!");   
34}
   
35  
36p1.print();  //i am p1(p1的print方法仍旧是自己的方法)   
37p2.print();  //new print method!(p2的print方法随着超类方法的改变而改变) 

        看过一篇文章介绍说javascript中对象的prototype属性相当于java中的static变量,可以被这个类下的所有对象共用。而上面的例子似乎表明实际情况并不是这样:在JS中,当我们用new操作符创建了一个类的实例对象后,它的方法和属性确实继承了类的prototype属性,类的prototype属性
中定义的方法和属性,确实可以被这些实例对象直接引用。但是,当我们对这些实例对象的属性和方法重新赋值或定义后,那么实例对象的属性或方法就不再指向类的prototype属性中定义的属性和方法。此时,即使再对类的prototype属性中相应的方法或属性做修改,也不会反应在实例对象身上。这就解释了上面的例子:一开始,用new操作符生成了两个对象p1,p2,他们的age属性和print方法都来自(继承于)Person类的prototype属性.然后,我们修改了p1的age属性,后面对Person类的prototype属性中的age重新赋值(Person.prototype.age = 22),p1的age属性并不会随之改变,但是p2的age属性却随之发生了变化,因为p2的age属性还是引自Person类的prototype属性。同样的情况在后面的print方法中也体现了出来。

        通过上面的介绍,我们知道prototype属性在javascript中模拟了父类(超类)的角色,在js中体现面向对象的思想,prototype属性是非常关键的。
posted @ 2009-10-20 11:27 Brian 阅读(189) | 评论 (0)编辑 收藏
        本文转载于javaeye(http://www.javaeye.com/wiki/Object_Oriented_JavaScript/1279-javascript-object-oriented-technology-one),只进行了重新排版以便收藏。
        文中所有英文语句(程序语句除外),都引自<<javascript-the definitive guide,5th edition>>。

------------------------------------------------------------------------------------
函数
        javascript函数相信大家都写过不少了,所以我们这里只是简单介绍一下。
        创建函数:
                function f(x) {........}
                var f = function(x) {......}
        上面这两种形式都可以创建名为f()的函数,不过后一种形式可以创建匿名函数。函数定义时可以设置参数,如果传给函数的参数个数不够,则从最左边起依次对应,其余的用undefined赋值,如果传给函数的参数多于函数定义参数的个数,则多出的参数被忽略。

1function myprint(s1,s2,s3) {   
2    alert(s1+"_"+s2+"_"+s3);   
3}
   
4myprin();      //undefined_undefined_undefined   
5myprint("string1","string2"); //string1_string2_undefined   
6myprint("string1","string2","string3","string4"); //string1_string2_string3  

        因此,对于定义好的函数,我们不能指望调用者将所有的参数全部传进来。对于那些必须用到的参数应该在函数体中加以检测(用!操作符),或者设置默认值然后同参数进行或(||)操作来取得参数。

 1function myprint(s1,person) {   
 2    var defaultperson = {   //默认person对象   
 3        "name":"name1",   
 4    "age":18,   
 5    "sex":"female"  
 6    }
;   
 7    if(!s1) {    //s1不允许为空   
 8        alert("s1 must be input!");   
 9    return false;   
10    }
   
11    person = person || defaultperson;  //接受person对象参数   
12    alert(s1+"_"+person.name+":"+person.age+":"+person.sex);   
13}
;   
14  
15myprint(); //s1 must be input!   
16myprint("s1"); //s1_name1:18:female   
17myprint("s1",{"name":"sdcyst","age":23,"sex":"male"});  //s1_sdcyst:23:male  

        函数的arguments属性
        在每一个函数体的内部,都有一个arguments标识符,这个标识符代表了一个Arguments对象。Arguments对象非常类似于Array(数组)对象,比如都有length属性,访问它的值用"[]"操作符利用索引来访问参数值。但是,二者是完全不同的东西,仅仅是表面上有共同点而已(比如说修改Arguments对象的length属性并不会改变它的长度)。
1function myargs() {   
2    alert(arguments.length);   
3    alert(arguments[0]);   
4}
   
5myargs();   //0  ---  undefined   
6myargs("1",[1,2]);  //2 --- 1  

         Arguments对象有一个callee属性,标示了当前Arguments对象所在的方法。可以使用它来实现匿名函数的内部递归调用。

1function(x) {   
2    if (x <= 1return 1;   
3    return x * arguments.callee(x-1);   
4}
  (section8.2

------------------------------------------------------------------

Method--方法
        方法就是函数。我们知道,每一个对象都包含0个或多个属性,属性可以是任意类型,当然也包括对象。函数本身就是一种对象,因此我们完全可以把一个函数放到一个对象里面,此时,这个函数就成了对象的一个方法。此后如果要使用该方法,则可以通过对象名利用"."操作符来实现。

1var obj = {f0:function(){alert("f0");}}//对象包含一个方法   
2function f1() {alert("f1");}   
3obj.f1 = f1;    //为对象添加方法   
4  
5obj.f0(); //f0  f0是obj的方法   
6obj.f1(); //f1  f1是obj的方法   
7f1();     //f1  f1同时又是一个函数,可以直接调用   
8f0();     //f0仅仅是obj的方法,只能通过对象来调用  

        方法的调用需要对象的支持,那么在方法中如何获取对象的属性呢?this!this关键字我们已经很熟悉了,在javascript的方法中,我们可以用this来取得对方法调用者(对象)的引用,从而获取方法调用者的各种属性。

1var obj = {"name":"NAME","sex":"female"};   
2obj.print = function() {  //为对象添加方法   
3    alert(this.name + "_" + this["sex"]);   
4}
;   
5obj.print();  //NAME_female   
6obj.sex = "male";   
7obj.print();  //NAME_male  

    下面我们来一个更加面向对象的例子:

 1var person = {name:"defaultname",   
 2              setName:function(s){   
 3              this.name = s;   
 4          }
,   
 5          "printName":function(){   
 6              alert(this.name);   
 7          }
}
   
 8person.printName();       //defaultname   
 9person.setName("newName");   
10person.printName();       //newName  

        在上面的例子中,完全可以用person.name=..来直接改变person的name属性,在此我们只是为了展示一下刚才提到的内容。
        另一种改变person属性的方法就是:定义一个function,接收两个参数,一个是person,一个是name的值,看起来像是这样:changeName(person,"newName")。哪种方法好呢?很明显,例子中的方法更形象,更直观一些,而且好像有了那么一点面向对象的影子。

        再次强调一下,方法(Method)本身就是是函数(function),只不过方法的使用更受限制。在后面的篇幅中,如果提到函数,那么提到的内容同样适用于方法,反之则不尽然。

函数的prototype属性
        每一个函数都包含了一个prototype(原型)属性,这个属性构成了javascript面向对象的核心基础。在后面我们会详细讨论。
posted @ 2009-10-20 11:04 Brian 阅读(183) | 评论 (0)编辑 收藏
        本文转载于javaeye(http://www.javaeye.com/wiki/Object_Oriented_JavaScript/1279-javascript-object-oriented-technology-one),只进行了重新排版以便收藏。
        文中所有英文语句(程序语句除外),都引自<<javascript-the definitive guide,5th edition>>。

------------------------------------------------------------------------------------
数组
        我们已经提到过,对象是无序数据的集合,而数组则是有序数据的集合,数组中的数据(元素)通过索引(从0开始)来访问,数组中的数据可以是任何的数据类型。数组本身仍旧是对象,但是由于数组的很多特性,通常情况下把数组和对象区别开来分别对待(Throughout this book, objects and arrays are often treated as distinct datatypes.  This is a useful and reasonable simplification; you can treat objects and arrays as separate types for most of your JavaScript programming.To fully understand the behavior of objects and arrays, however, you have to know the truth: an array is nothing more than an object with a thin layer of extra functionality. You can see this with the typeof operator: applied to an array value, it returns the string "object".  --section7.5).
        创建数组可以用"[]"操作符,或者是用Array()构造函数来new一个。

1var array1 = [];  //创建空数组   
2var array2 = new Array();  //创建空数组   
3array1 = [1,"s",[3,4],{"name1":"NAME1"}]; //   
4alert(array1[2][1]);  //4   访问数组中的数组元素   
5alert(array1[3].name1); //NAME1 访问数组中的对象   
6alert(array1[8]);   //undefined   
7array2 = [,,];  //没有数值填入只有逗号,则对应索引处的元素为undefined   
8alert(array2.length); //3   
9alert(array2[1]);     //undefined

        用new Array()来创建数组时,可以指定一个默认的大小,其中的值此时为undefined,以后可以再给他们赋值.但是由于javascript中的数组的长度是可以任意改变的,同时数组中的内容也是可以任意改变的,因此这个初始化的长度实际上对数组没有任何的约束力。对于一个数组,如果对超过它最大长度的索引赋值,则会改变数组的长度,同时会对没有赋值
的索引处赋值undefined,看下面的例子:

1var array = new Array(10);   
2alert(array.length);   //10   
3alert(array[4]);       //undefined   
4array[100= "100th";  //这个操作会改变数组的长度,同时将10-99索引对应的值设为undefined   
5alert(array.length);   //101   
6alert(array[87]);      //undefined  

         可以用delete操作符删除数组的元素,注意这个删除仅仅是将数组在该位置的元素设为undefined,数组的长度并没有改变。我们已经使用过了数组的length属性,length属性是一个可以读/写的属性,也就是说我们可以通过改变数组的length属性来任意的改变数组的长度。如果将length设为小于数组长度的值,则原数组中索引大于length-1的值都会被删除。如果length的值大于原始数组的长度,则在它们之间的值设为undefined。

 1var array = new Array("n1","n2","n3","n4","n5");  //五个元素的数组   
 2var astring = "";   
 3for(var i=0; i<array.length; i++{           //循环数组元素   
 4    astring += array[i];   
 5}
   
 6alert(astring);       //n1n2n3n4n5   
 7delete array[3];                   //删除数组元素的值   
 8alert(array.length + "_" + array[3])  //5_undefined   
 9  
10array.length = 3;    //缩减数组的长度   
11alert(array[3]);     //undefined   
12array.length = 8;    //扩充数组的长度   
13alert(array[4]);     //undefined  

        对于数组的其他方法诸如join/reverse等等,在这就不再一一举例。

        通过上面的解释,我们已经知道,对象的属性值是通过属性的名字(字符串类型)来获取,而数组的元素是通过索引(整数型 0~~2**32-1)来得到值。数组本身也是一个对象,所以对象属性的操作也完全适合于数组。

1var array = new Array("no1","no2");   
2array["po"= "props1";   
3alert(array.length);   //2   
4//对于数组来说,array[0]同array["0"]效果是一样的(?不确定,测试时如此)   
5alert(array[0+ "_" + array["1"+ "_" + array.po);//no1_no2_props1  
posted @ 2009-10-20 10:46 Brian 阅读(292) | 评论 (2)编辑 收藏
          本文转载于javaeye(http://www.javaeye.com/wiki/Object_Oriented_JavaScript/1279-javascript-object-oriented-technology-one),只进行了重新排版以便收藏。
          文中所有英文语句(程序语句除外),都引自<<javascript-the definitive guide,5th edition>>。

------------------------------------------------------------------------------------
对象和数组(Objects and Arrays)
        什么是对象?把一些"名字-属性"的组合放在一个单元里面,就组成了一个对象。我们可以理解为javascript中的对象就是一些"键-值"对的集合(An object is a collection of named values. These named values are usually referred to as properties of the object.--Section3.5)。
        "名字"只能是string类型,不能是其他类型,而属性的类型则是任意的(数字/字符串/其他对象..)。可以用new Object()来创建一个空对象,也可以简单的用"{}"来创建一个空对象,这两者的作用是等同的。
         
1var emptyObject1 = {};           //创建空对象   
2var emptyObject2 = new Object(); //创建空对象   
3var person = {"name":"sdcyst",   
4          "age":18,   
5          "sex":"male"}
;     //创建一个包含初始值的对象person   
6alert(person.name);              //sdcyst   
7alert(person["age"]);            //18  
    
        从上面的例子我们也可以看到,访问一个对象的属性,可以简单的用对象名加"."后加属性的名字,也可以用"[]"操作符来获取,此时在[]里面的属性名字要加引号,这是因为对象中的索引都是字符串类型的。javasript对象中属性的个数是可变的,在创建了一个对象之后可以随时对它赋予任何的属性。

1var person = {};   
2person.name = "sdcyst";   
3person["age"= 18;   
4alert(person.name + "__" + person.age); //sdcyst__18   
5  
6var _person = {name:"balala","age":23}//在构建一个对象时,属性的名字可以不用引号来标注(name),   
7                    //但是仍旧是一个字符串类型.在访问的时候[]内仍旧需要引号   
8alert(_person["name"+ "__" + person.age); //balala__23   
9alert(_person[name]);                   //undefinied  
   
        通过"."操作符获取对象的属性,必须得知道属性的名字。一般来说"[]"操作符获取对象属性的功能更强大一些,可以在[]中放入一些表达式来取属性的值,比如可以用在循环控制语句中,而"."操作符则没有这种灵活性。

 1var name = {"name1":"NAME1","name2":"NAME2","name3":"NAME3","name4":"NAME4"};   
 2var namestring = "";   
 3for(var props in name) {  //循环name对象中的属性名字   
 4    namestring += name[props];   
 5}
   
 6alert(namestring);  //NAME1NAME2NAME3NAME4   
 7  
 8namestring = "";   
 9for(var i=0; i<4; i++{   
10    namestring += name["name"+(i+1)];   
11}
   
12alert(namestring);  //NAME1NAME2NAME3NAME4  

        delete操作符可以删除对象中的某个属性,判断某个属性是否存在可以使用"in"操作符。

 1var name = {"name1":"NAME1","name2":"NAME2","name3":"NAME3","name4":"NAME4"};   
 2var namestring = "";   
 3for(var props in name) {  //循环name对象中的属性名字   
 4    namestring += name[props];   
 5}
   
 6alert(namestring);  //NAME1NAME2NAME3NAME4   
 7  
 8delete name.name1;  //删除name1属性   
 9delete name["name3"];  //删除name3属性   
10namestring = "";   
11for(var props in name) {  //循环name对象中的属性名字   
12    namestring += name[props];   
13}
   
14alert(namestring);  //NAME2NAME4   
15  
16alert("name1" in name); //false   
17alert("name4" in name); //true  

        需要注意,对象中的属性是没有顺序的。

对象的constructor属性
        每一个javascript对象都有一个constructor属性。这个属性对应了对象初始化时的构造函数(函数也是对象)。

1var date = new Date();   
2alert(date.constructor);  //Date   
3alert(date.constructor == "Date");  //false   
4alert(date.constructor == Date);  //true  
posted @ 2009-10-20 10:37 Brian 阅读(220) | 评论 (0)编辑 收藏

公告


导航

<2009年10月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

统计

常用链接

留言簿(4)

随笔分类

随笔档案

收藏夹

搜索

最新评论

阅读排行榜

评论排行榜