当前位置 : 主页 > 网页制作 > Dojo >

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

来源:互联网 收集:自由互联 发布时间:2021-06-15
在Dojo 工具箱中, dojo/_base/declare模块是创建类的基础。 declare允许开发者实现类多继承,从而创建有弹性的(灵活的)代码, 避免写重复的代码。 Dojo, Digit, Dojox模块都使用了declare. 在这

在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, MyOtherClass, 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 和 创建类的细节, 查看以下资源:
  • dojo/declare
  • dojo/_base/lang::mixin
  • Writing Your Own Widget
网友评论