与java类一样,在Dojo里也可以定义constructor 构造函数,在创建一个实例时可以对需要的属性进行初始化。
//定义一个类Mqsy_yj
var Mqsy_YJ =
declare(null, { //
The default username username:
"yanjun", //
The constructor constructor:
function(args){ declare.safeMixin(this,args); }});
//实例化
var myIns1 = new
Mqsy_YJ();
var myIns2 = new
Mqsy_YJ({ username:
"yourname"});
alert(myIns1.username);//yanjun
alert(myIns2.username);//yourname
args是一个JSON结构,可以包含任意多个需要初始化的属性的key:value值对。
this是指当前实例范围,不影响其他实例。declare.safeMixin可能有其他用途,这里使用很简单,不详解。
类似于java的super.method()来调用父类的方法,Dojo则可以通过this.inherited来实现。
// Define class Avar A = declare(null,
{ myMethod:
function(){ console.log("Hello!"); }});// Define class Bvar 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 Bvar myB = new
B();myB.myMethod();// Would output:// Hello! //
World!
this.inherited(arguments);中arguments指的就是在父类中定义的myMethod。