dojo 四 类的构造函数和父方法的调用

时间:2023-03-08 22:00:11
dojo 四 类的构造函数和父方法的调用

与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 A
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(arguments);中arguments指的就是在父类中定义的myMethod。