DOJO 基本原理 之 dojo/_base/declare<7>

在Dojo 工具箱中, dojo/_base/declare模块是创建类的基础。 declare允许开发者实现类多继承,从而创建有弹性的(灵活的)代码, 避免写重复的代码。 Dojo,Digit,Dojox模块都使用了declare. 在这个指南中,你将知道你为什么也需要它。

开始

在开始之前你需要先看看 modules 指南.

Dojo类创建的基础

declare 函数是在dojo/_base/declare模块中定义。 declare接受三个参数: className,superClass 和 properties.

类名(className)

className参数是要创建的这个类的名字,也包括它的命名空间。命名类(给定了className,相对的为匿名类, Named Class)的名字会存在于全局作用域, className也可以通过命名空间来表示继承链。

命名类(Named Class)
// Create a new class named "mynamespace.MyClass"
declare("mynamespace.MyClass",null,{
 
    // Custom properties and methods here
 
});

一个类命名为 mynamespace.MyClass,现在可以在全局作用域类访问。
!* 命名类应该仅在使用Dojo parser创建。 其它的类最好省略className参数。

匿名类( "Anonymous" Class)

// Create a scoped,anonymous class
var MyClass = declare(null,{
 
    // Custom properties and methods here
 
});

MyClass 现在只在给定的作用域内有效。

父类(或多个父类)

SuperClass 参数可以为空, 单个已存在的类,或者多个类组成的数组。 如果一个新类要继承多个类,那么在列表的第一个类将是新创建类的原型,剩下的被认为为"多态"(复制它们的属性和方法到新类)。

不继承

var MyClass = declare(null,{
 
    // Custom properties and methods here
 
});

null 表示 这个类不继承任何其它类。

单继承

var MySubClass = declare(MyClass,{
 
    // MySubClass now has all of MyClass's properties and methods
    // These properties and methods override parent's
 
});

新的MySubClass 将继承 MyClass的属性和方法。 父类的方法或者属性可以在第三个参数内,能过添加相同的键值来覆盖, 之后会讲解到。

多继承

var MyMultiSubClass = declare([
    MySubClass,MyOtherClass,MyMixinClass
],{
 
    // MyMultiSubClass now has all of the properties and methods from:
    // MySubClass,and MyMixinClass
 
});

若是一个数组则表示多继承。 属性和方法被继承时是从左到右。 在数组中的第一个类作为新类的原型, 随后的类被混合到新类中。
!* 如果一个属性或者方法在多个被继承的类中, 那么最后一个类的属性或者方法会被使用

属性和方法对象

declare方法的最后的参数是包含这个类原型方法和原型属性的一个对象。 此参数提供的属性或方法如果跟被继承的类的属性或方法同名,那么会重写同名的方法或属性。


自定义的属性和方法

// Class with custom properties and methods
var MyClass = declare(MyParentClass,{
	// Any property
	myProperty1: 12,// Another
	myOtherProperty: "Hello",// A method
	myMethod: function(){

		// Perform any functionality here

		return result;
	}
});

例子: 类的创建和继承基础

以下的代码创建了一个继承自 digit/form/Button的窗口部件
define([
    "dojo/_base/declare","dijit/form/Button"
],function(declare,Button){
    return declare("mynamespace.Button",Button,{
        label: "My Button",onClick: function(evt){
            console.log("I was clicked!");
            this.inherited(arguments);
        }
    });
});

通过上面代码片断, 我们可以知道:
  • 类的名字为mynamespace.Button
  • 这个类可以通过全局变量mynamespace.Button或者模块的返回值引用
  • 这个类继承digit/form/Button
  • 这个类设置了自己的属性和方法。
之后通过构造函数 constructor 方法更深入的学习,如何创建一个Dojo 类。

构造函数

类中特别的一个方法就是 constructor 方法, constructor 方法会在类的实例化时触发,在新对象的作域名内执行。 意思是 this关键词会指向这个类的实例。 而不是类。 constructor 也接受实例化指定的参数。
// Create a new class
var Twitter = declare(null,{
    // The default username
    username: "defaultUser",// The constructor
    constructor: function(args){
        declare.safeMixin(this,args);//将传入的参数混入到实例中对象中
    }
});

接下来实例化一个对象
var myInstance = new Twitter();

这个对象的 username 将是 "defaultUser"(类定义时指定),因为没有给这个实例指提供指定的设置。 可以利用 safeMixin方法,来提供一个username参数:
var myInstance = new Twitter({
    username: "sitepen"
});

现在这个实例可以使用sitepen 作为它的 username.

declare.safeMixin 在类创建和继承时非常有用。 如它的API文档声明一样:

“This function is used to mix in properties like lang._mixin does,but it skips a constructor property and decorates functions like dojo/_base/declare does. It is meant to be used with classes and objects produced with dojo/_base/declare. Functions mixed in with declare.safeMixin can use this.inherited() like normal methods. This function is used to implement extend() method of a constructor produced with declare().”

继承

如上所述, 继承是被定义在declare函数中的第二个参数内,新的类会从左到右继承父类的属性和方法。 后面类的属性和方法具有最高的优先权。 看看以下的例子:
// Define class A
var A = declare(null,{
    // A few properties...
    propertyA: "Yes",propertyB: 2
});
 
// Define class B
var B = declare(A,{
    // A few properties...
    propertyA: "Maybe",propertyB: 1,propertyC: true
});
 
// Define class C
var C = declare([mynamespace.A,mynamespace.B],{
    // A few properties...
    propertyA: "No",propertyB: 99,propertyD: false
});

这个继承类的属性结果是:
// Create an instance
var instance = new C();
 
// instance.propertyA = "No" // overridden by B,then by C
// instance.propertyB = 99 // overridden by B,then by C
// instance.propertyC = true // kept from B
// instance.propertyD = false // created by C

这里需要理解原型继承非常重要。 当检索一个对象实例的属性时, 会首先检查实例自已的定义的属性。 如果没有, 会查找原型链, 如果原型链中的第一个对象有定义该属性,直接返回。 当一个值是赋值给一个对象实例时,它只在这个实例上有效,而不会是原型链。 这样的话,所有共享同一个原型的对象,会获得原型上相同的值。除非是对象实例上的值。 这使得在你的类声明中很容易给原始类型(number,string,boolean) 定义默认的值, 然后在实例对像中可以直接修改。 可是,如果你给原型上的属性分配的是一个对象(Object,Array), 那么每一个实例会共享同一个值。
var MyClass = declare(null,{
    primitiveVal: 5,objectVal: [1,2,3]
});
 
var obj1 = new MyClass();
var obj2 = new MyClass();
 
// both return the same value from the prototype
obj1.primitiveVal === 5; // true
obj2.primitiveVal === 5; // true
 
// obj2 gets its own property (prototype remains unchanged)
obj2.primitiveVal = 10;
 
// obj1 still gets its value from the prototype
obj1.primitiveVal === 5; // true
obj2.primitiveVal === 10; // true
 
// both point to the array on the prototype,// neither instance has its own array at this point
obj1.objectVal === obj2.objectVal; // true
 
// obj2 manipulates the prototype's array
obj2.objectVal.push(4);
// obj2's manipulation is reflected in obj1 since the array
// is shared by all instances from the prototype
obj1.objectVal.length === 4; // true
obj1.objectVal[3] === 4; // true
 
// only assignment of the property itself (not manipulation of object
// properties) creates an instance-specific property
obj2.objectVal = [];
obj1.objectVal === obj2.objectVal; // false

为了避免非故意的修改共享的数组或者对象, 对象的属性应该声名为null 然后在构造函数中对它初始化。
declare(null,{
    // not strictly necessary,but good practice
    // for readability to declare all properties
    memberList: null,roomMap: null,constructor: function () {
        // initializing these properties with values in the constructor
        // ensures that they ready for use by other methods
        // (and are not null or undefined)
        this.memberList = [];
        this.roomMap = {};
    }
});

参考 dojo/_base/declare 文档获得更多信息

this.inherited

虽然完成重写一个方法确实有用, 但每一个类的的构造函数都应该执行它继承链中的父类构造函数,以保持它原始的功能。 这样this.inherited(arguments)语句就派上用场了。 this.inherited(arguments)语句调用父类的同名方法。 考虑下面的例子:
var A = declare(null,{
    myMethod: function(){
        console.log("Hello!");
    }
});
 
// Define class B
var B = declare(A,{
    myMethod: function(){
        // Call A's myMethod
        this.inherited(arguments); // arguments provided to A's myMethod
        console.log("World!");
    }
});
 
// Create an instance of B
var myB = new B();
myB.myMethod();
 
 
// Would output:
//      Hello!
//      World!

!* this.inherited 方法可在子类代码中的任何时间调用。 不管你是在子函数的中部,甚至是底部调用都是允许的( Java中都是在最顶部通过 super调用), 这就是说,你不应该在构造函数内调用它。

总结

declare函数是创建一个模块的关键, 使得Dojo Toolkit可以重用类。 declare允许通过多重继承和其它的一些属性和方法来重新创建一个复杂的类。 更好的是, declare很容易使用, 避免开发者重复的写相同的代码。

dojo/_base/declare 资源

关于更多 declare 和 创建类的细节, 查看以下资源:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


我有一个网格,可以根据更大的树结构编辑小块数据.为了更容易知道用户保存了什么,我希望当用户第一次看到网格时,网格处于不可编辑状态.当用户准备好后,他们可以单击编辑按钮,这将使网格的某些部分可编辑.然后,有一个保存或取消按钮可以保存更改或还原.在大多数情况下它是有效的.但
我即将开始开发一款教育性的视频游戏.我已经决定以一种我可以轻松打包为Web,Mobiles和可能的Standalone版本的方式来实现这一目标.我不想使用Flash.因此,我确信(无论如何我会听取建议)使用JavaScript和SVG.我正在对这个问题进行大量研究,但我很难把各个部分放在一起.我知道Raphae
我正在使用带有Grails2.3.9的Dojo1.9.DojoNumberTextBox小部件–我在表单中使用–将固定格式(JavaScript基本格式)的实数值(例如:12.56)设置为HTML表单输入字段(但根据浏览器区域设置显示/编辑它们,所以用户总是看到格式正确的数字).另一方面,Grails期望输入字段根据浏览器
1.引言鉴于个人需求的转变,本系列将记录自学arcgisapiforjavaScript的学习历程,本篇将从最开始的arcgisapiforjavaScript部署开始,个人声明:博文不在传道受业解惑,旨在方便日后复习查阅。由于是自学,文章中可能会出现一些纰漏,请留言指出,不必留有情面哦!2.下载ArcGISforDe
我正在阅读使用dojo’sdeclare进行类创建的语法.描述令人困惑:Thedeclarefunctionisdefinedinthedojo/_base/declaremodule.declareacceptsthreearguments:className,superClass,andproperties.ClassNameTheclassNameargumentrepresentsthenameofthec
我的团队由更多的java人员和JavaScript经验丰富组成.我知道这个问题曾多次被问到,但为了弄清楚我的事实,我需要澄清一些事情,因为我在客户端技术方面的经验非常有限.我们决定使用GWT而不是纯JavaScript框架构建我们的解决方案(假设有更多的Java经验).这些是支持我的决定的事实.>
路由dojo/framework/srcouting/README.mdcommitb682b06ace25eea86d190e56dd81042565b35ed1Dojo应用程序的路由路由FeaturesRoute配置路径参数RouterHistoryManagersHashHistoryStateHistoryMemoryHistoryOutletEventRouterContextInjectionOutl
请原谅我的无知,因为我对jquery并不熟悉.是否有dojo.connect()的等价物?我找到了这个解决方案:http:/hink-robot.com/2009/06/hitch-object-oriented-event-handlers-with-jquery/但是没有断开功能!你知道jquery的其他解决方案吗?有jquery.connect但这个插件在我的测试中不起作用.
与java类一样,在dojo里也可以定义constructor 构造函数,在创建一个实例时可以对需要的属性进行初始化。//定义一个类mqsy_yjvar mqsy_yj=declare(null,{     //thedefaultusername    username: "yanjun",          //theconstructor   
我一直在寻找一些最佳实践,并想知道Dojo是否具有框架特定的最佳实践,还是最好只使用通用的Javascript标准?特别是我主要是寻找一些功能和类评论的指导方针?解决方法:对于初学者来说,这是项目的风格指南:DojoStyleGuide
我有’05/17/2010’的价值我想通过使用dojo.date.locale将其作为“2010年5月17日”.我尝试过使用dojo.date.locale.parse,如下所示:x='05/17/2010'varx=dojo.date.locale.parse(x,{datePattern:"MM/dd/yyyy",selector:"date"});alert(x)这并没有给我所需的日期
我正在尝试创建一个包含函数的dojo类,这些函数又调用此类中的其他函数,如下所示:dojo.provide("my.drawing");dojo.declare("my.drawing",null,{constructor:function(/*Object*/args){dojo.safeMixin(this,args);this.container=args[0];
我知道你可以使用jQuery.noConflict为jQuery做这件事.有没有办法与Dojo做类似的事情?解决方法:我相信你可以.有关在页面上运行多个版本的Dojo,请参阅thispage.它很繁琐,但似乎是你正在寻找的东西.一般来说,Dojo和jQuery都非常小心,不会破坏彼此或其他任何人的变量名.
我有一个EnhancedGrid,用户经常使用复杂的过滤器.有没有办法允许用户保存或标记过滤器,以便将来可以轻松地重新应用它?我知道我可以通过编程方式设置过滤器,但我无法预测用户想要的过滤器.谢谢!编辑:自己做了一些进展…使用grid.getFilter()返回过滤器的JSON表示,然后使用json.strin
我有这个代码:dojo.declare("City",null,{constructor:function(cityid,cityinfo){}});dojo.declare("TPolyline",GPolyline,{constructor:function(points,color){},initialize:function(map){});应该是什
我遇到的问题是我的所有javascript错误似乎来自dojo.xd.js或子模块.我正在使用chrome调试器和许多dijit功能,如dijit.declaration和dojo.parser.这有点烦人,因为它很难找到简单的错误或滑倒.我希望我可以添加一个选项,允许我的调试器在我的非dojo代码中显示选项会发生的位置.我是
我正在使用DojoToolkit数字/解析函数来处理格式化和使用ICU模式语法解析字符串.有没有人知道有可能采取任意ICU模式字符串并以某种方式使用Dojo(或其他)库将其分解为它的部分(例如,对于数字模式,它可以被分解为小数位数,数千个分组等…).我希望这样做,而不需要让我的代码密切了
我有两个看似相关的问题,访问在不同的地方定义的javascript函数.我遇到的第一个问题是调用我在firgbug或safari控制台中定义的函数.我定义了一个名为getRed的函数,如下所示:functiongetRed(row,col){//dosomethingstuffandreturntheredvalueasa
我想添加一个在Ajax调用中指定的外部样式表.我已经找到了一种方法来使用jQuery(参见下面的示例),但是我需要使该方法适应dojoJavaScript框架.JQuery示例$('head').append('<linkrel="stylesheet"type="text/css"href="lightbox_stylesheet.css">');谢谢.解决方法:一旦你
我正在尝试使用dojo.connect将onMouseDown事件连接到图像,如:dojo.connect(dojo.byId("workpic"),"onMouseDown",workpicDown);functionworkpicDown(){alert("mousedown");}类似的代码几行后,我将onMouse*事件连接到dojo.body确实完全正常工作.但是当我点击图像时