Make class constants available before class instantiation
Reported by Nesterenko Dmitry | July 4th, 2008 @ 10:54 PM
I just wanted to make my class constant available just after class declaration and before class instantiation. I stucked when tryed to implement something like:
var ExampleCls = Class.create({
CLS_CONST: 'CLS_CONST'
})
alert(ExampleCls.CLS_CONST) // is undefined, but 'CLS_CONST' expected
I solve this problem redefining default #Class.create function with next block of code:
var clonedCreate = Class['create']
Class.create = function() {
var klass = clonedCreate.apply(this, arguments);
/**
- Setup constants
*/
var properties = $A(arguments);
if (Object.isFunction(properties[0])) {
properties.shift();
}
for (var property in properties[0]) {
if (property.indexOf('_') !== 0 && property !== 'initialize') {
var item = properties[0][property];
if (!(item instanceof Function)) {
klass[property] = item;
}
}
}
return klass
}
May be this proposition will be usefull for you?
Comments and changes to this ticket
-

Nesterenko Dmitry July 4th, 2008 @ 10:57 PM
Code formatting is broken. Plese see code in attachement
-

Nesterenko Dmitry July 4th, 2008 @ 10:58 PM
- no changes were found...
-
Juriy Zaytsev July 5th, 2008 @ 07:19 PM
- → State changed from new to not_for_core
Dmitry,
"Static" properties are simply defined on constructors:
var ExampleCls = Class.create({ initialize: function(){ ... } ... }); ExampleCls.CLS_CONST = 'CLS_CONST';Any property of an object passed to Class.create (besides "initialize") becomes a shared instance one.
var ExampleCls = Class.create({ ... ExampleCls.CLS_CONST: 'CLS_CONST'; ... }); new ExampleCls().CLS_CONST; // 'CLS_CONST' -

-
Juriy Zaytsev July 7th, 2008 @ 05:12 PM
Sorry, my example was wrong : /
Here you go:
var ExampleCls = Class.create({ CLS_CONST: 'CLS_CONST', foo: function() { return this.CLS_CONST; } }); new ExampleCls().foo(); // 'CLS_CONST'
Please Login or create a free account to add a new comment.
You can update this ticket by sending an email to from your email client. (help)
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
The Prototype JavaScript library.
