考虑这个例子:
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.app.Application-static-method-getName
Ext.define('My.cool.Class', {
constructor: function() {
alert(this.self.getName()); // alerts 'My.cool.Class'
}
});
My.cool.Class.getName(); // 'My.cool.Class'
Run Code Online (Sandbox Code Playgroud)
self这个例子中指的是什么?我如何,本文档中,知道何时使用this以及何时self以及何时this.self?为什么这不起作用:
this.getName()
Run Code Online (Sandbox Code Playgroud)
要么
self.getName()
Run Code Online (Sandbox Code Playgroud)
我对此的想法是self指的是对象的类,所以我需要这样做的唯一原因是因为getName()方法是静态的,所以我(有点)不是从对象调用它,而是从类调用它.我对吗?我呢?哈?哈?我呢?:d
this.self指的是类对象.这意味着this.self === My.cool.Class.因此,您可以My.cool.Class通过调用实例化新对象new this.self().
之所以this.getName()不起作用是因为在JS中,静态属性/方法在实例中不可用.
例:
var Class = function(){};
Class.prototype = {};
Class.staticMethod = function(){ alert('static method'); };
Class.prototype.instanceMethod = function(){ alert('instance method'); };
var instance = new Class();
Class.staticMethod(); // works
Class.instanceMethod(); // doesn't work
instance.staticMethod(); // doesn't work
instance.instanceMethod(); // works
Run Code Online (Sandbox Code Playgroud)
即使在静态上下文中,子类中也不提供静态属性/方法.
例:
Ext.define('One', {
instanceMethod: function() { alert('Instance One'); }
});
Ext.apply(One, {
staticMethod: function() { alert('Static One'); }
});
Ext.define('Two', {
extend: 'One'
});
One.staticMethod(); // works
Two.staticMethod(); // doesn't work
Run Code Online (Sandbox Code Playgroud)
getName方法可用的原因My.cool.Class是因为从方法中的Ext.Base类复制ExtClass.create(此类是私有的,它在API中不可见).