在extjs4.2语法中定义一个类

时间:2015-11-04 09:02:40

标签: extjs

我正在尝试研究extjs 4.2,在语法和跟踪,定义类和创建对象时,我真的可以使用一些帮助。有什么帮助吗?

Ext.define('Student', {
    name: 'unnamed',
    getName: function() {
        alert('Student name is ' + this.name);
    },
    constructor: function(studentName) {
        if (studentName) this.name = studentName;
    },
    statics: {
        staticMethod: function() {
            alert("This is static method of student class");
        }
    }
}

);

//create an object using 'new'
var student1 = new Student('ABC');
student1.getName();

//create an object using Ext.create
var student2 = Ext.create('Student', 'XYZ');
student2.getName();

//create an object using className.create()
var student3 = Student.create('123');
student3.getName();

//call static method by className.staticMethodName()
Student.staticMethod();

1 个答案:

答案 0 :(得分:2)

对代码进行一些评论,以便您更好地理解它:

// Class Student definition
Ext.define('Student', {
    name: 'unnamed',        // a basic string property
    getName: function() {   // a basic function to display a message with the name
        alert('Student name is ' + this.name);
    },

    constructor: function(studentName) {    // The constructor function with the name of the student as parameter
        if (studentName) this.name = studentName;   // If the name is given then assign it to the instance
    },

    statics: {      // Begin of static functions declaration

        staticMethod: function() {  // a static function called "staticMethod"
            alert("This is static method of student class");
        }
    }               // End of static functions declaration
});
// End of class definition

//create an object using 'new' with the name "ABC"
var student1 = new Student('ABC');
student1.getName(); // Should display a message alert with text: "Student name is ABC"

//create an object using Ext.create
var student2 = Ext.create('Student', 'XYZ');    // The second parameter should be ignored
student2.getName(); // Should display a message alert with text: "Student name is Student"

//create an object using className.create()
var student3 = Student.create('123');
student3.getName(); // Should display a message alert with text: "Student name is 123"

//call static method by className.staticMethodName()
Student.staticMethod(); // call the static function declared in Student.
                        // This does not need any class instance