RefineJS
Powerful and flexible generator objects with inheritable
This mini-library adds/expands the possibilities for objects in JavaScript or to be more precise, makes all the routine work on the objects for you. Namely:
And some other features for the convenience of working with objects in JavaScript...
Programming Interface - API
refine()
or refinejs()
Method to create objects.
-
Return value:
type: [object|function] - return object instance when calling the operator new, otherwise returns an internal constructor (function) "refine-constructor".
Example:
var foo = new refine();
similar:
var Foo = refine();
var foo = new Foo();
Parameters:
- [object] - context
- Context where it will be built refine-constructor. You must specify the name cName.
- [string] - cName
- A string specifying the name of refine-constructor
- [array] - extend
- An array of objects that need to expand/improve or refine-constructors from which to inherit.
- [object|boolean] - options
- Object with options indicating the conditions of the object creation or
true
indicating that you need to create a compact object without adding extra properties are needed for the library. - [object|function] - structure
- Structure of a new object or function that should return the object. Function is indicated for the implementation of encapsulation or for getting the general settings for the current object.
Examples
A method for implementing an object with properties that are read-only:
var Rect = refine(function(left, top, right, bottom) {
return {
left: {
get: function() {
return left|0;
}
},
top: {
get: function() {
return top|0;
}
},
right: {
get: function() {
return right|0;
}
},
bottom: {
get: function() {
return bottom|0;
}
},
width: {
get: function() {
return (right|0) - (left|0);
}
},
height: {
get: function() {
return (bottom|0) - (top|0);
}
},
}
});
Thus, we have a constructor Rect()
which creates a rect
with properties having a read-only attribute. They can not be overridden but can be read. This example illustrates how to implement the standard JavaScript access methods. But there are more concise and compact way:
var Rect = refine(function(left, top, right, bottom) {
return {
"get left": left|0,
"get top": top|0,
"get right": right|0,
"get bottom": bottom|0,
"get width": (right|0) - (left|0),
"get height": (bottom|0) - (top|0)
}
});
So that the first and second example will work identically. And accordingly:
var rect = new Rect(10, 20, 100, 200);
console.log(JSON.stringify(rect));
console.log(rect.width);
rect.width = 40;
console.log(rect.width);
Detailed description will be available soon...
РУССКИЙ
Мощный и гибкий генератор объектов с возможностью наследования
Эта мини-библиотека добавляет/расширяет возможности для объектов в JavaScript или если быть точнее, делает всю рутинную работу над объектами за вас. А именно:
И некоторые другие возможности для удобства работы с объектами в JavaScript...
Интерфейс программирования - API
refine()
или refinejs()
Основной метод, конструктор объектов.
-
Возвращаемое значение:
type: [object|function] - вернет рабочий объект при вызове метода с оператором new, иначе вернет внутренний конструктор (функцию) "refine-конструктор".
Пример:
var foo = new refine();
аналогично выполнению:
var Foo = refine();
var foo = new Foo();
Параметры конструктора объектов:
- [object] - context
- Контекст в котором будет создан refine-конструктор при условии если задано его имя cName
- [string] - cName
- Строка определяющая имя refine-конструктора
- [array] - extend
- Массив объектов которые нужно расширить/улучшить или refine-конструкторов от которых нужно наследоваться.
- [object|boolean] - options
- Объект с опциями, указывающими об условиях создания объекта, либо
true
указывающее на то что нужно создать компактный объект, не добавляя лишних свойств, которые нужны для работы библиотеки. - [object|function] - structure
- Структура создаваемого объекта, если задана функция, то она должна вернуть объект. Функция указывается для реализации Инкапсуляции и получения переданных общих настроек для текущего конструктора.
Примеры
Способ реализации объекта со свойствами, доступными только для чтения:
var Rect = refine(function(left, top, right, bottom) {
return {
left: {
get: function() {
return left|0;
}
},
top: {
get: function() {
return top|0;
}
},
right: {
get: function() {
return right|0;
}
},
bottom: {
get: function() {
return bottom|0;
}
},
width: {
get: function() {
return (right|0) - (left|0);
}
},
height: {
get: function() {
return (bottom|0) - (top|0);
}
},
}
});
Таким образом, мы имеем конструктор Rect()
который создает объект rect
со свойствами имеющими атрибут только чтение. Их нельзя переопределить но можно читать. Этот пример иллюстрирует стандартный JavaScript способ реализации методов доступа. Но есть более лаконичный и компактный способ:
var Rect = refine(function(left, top, right, bottom) {
return {
"get left": left|0,
"get top": top|0,
"get right": right|0,
"get bottom": bottom|0,
"get width": (right|0) - (left|0),
"get height": (bottom|0) - (top|0)
}
});
Таким образом что первый что второй вариант, будут работать идентично. И соответственно вызов:
var rect = new Rect(10, 20, 100, 200);
console.log(JSON.stringify(rect));
console.log(rect.width);
rect.width = 40;
console.log(rect.width);
Detailed description will be available soon...