Product
Introducing SSO
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
refinejs
Advanced tools
Readme
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:
Cross-browser compatibility
Encapsulation
Access methods
To access the data fields are in use special methods called accessors. Such methods return value of a field or records a new value in the field.
Have limitations in Internet Explorer 8 and earlier versions. More details about the restrictions described in the chapter "Creating access methods".
Expansion/Override
Inheritance (prototyping)
Virtual inheritance
And some other features for the convenience of working with objects in JavaScript...
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(); // return object instance
similar:
var Foo = refine(); // return refine-constructor
var foo = new Foo(); // return object instance
true
indicating that you need to create a compact object without adding extra properties are needed for the library.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));
// {"left":10,"top":20,"right":100,"bottom":200,"width":90,"height":180}
// work with object
console.log(rect.width); // 90
rect.width = 40; // override property
console.log(rect.width); // 90 - override failed, the value remains unchanged
Эта мини-библиотека добавляет/расширяет возможности для объектов в JavaScript или если быть точнее, делает всю рутинную работу над объектами за вас. А именно:
Кросс-браузерность
Инкапсуляция
Методы доступа
Для доступа к находящимся в полях данным используются специальные методы, называемые методами доступа. Такие методы либо возвращают значение того или иного поля, либо производят запись в это поле нового значения.
Создают ряд ограничений в Internet Explorer 8 и более ранних версиях. Подробнее об ограничениях будет описано в главе "Создание методов доступа".
Расширение/Переопределение
Наследование (прототипирование)
Виртуальное наследование
И некоторые другие возможности для удобства работы с объектами в JavaScript...
refine()
или refinejs()
Основной метод, конструктор объектов.
Возвращаемое значение:
type: [object|function] - вернет рабочий объект при вызове метода с оператором new, иначе вернет внутренний конструктор (функцию) "refine-конструктор".
Пример:
var foo = new refine(); // вернет готовый объект
аналогично выполнению:
var Foo = refine(); // вернет функцию конструктор
var foo = new Foo(); // вернет готовый объект
true
указывающее на то что нужно создать компактный объект, не добавляя лишних свойств, которые нужны для работы библиотеки.structure
:var Foo = refine({
foo: "something"
});
var foo = new Foo();
foo.foo; // something
// или
var Foo = refine(function() {
// приватные определения
var _foo = "something";
return {
foo: _foo
}
});
var foo = new Foo();
foo.foo; // something
name
:refine("Foo", {
foo: "something"
});
var foo = new Foo();
foo.foo; // something
context
:var context = {}; // контекст в котором будет создан refine-конструктор с именем Foo
refine(context, "Foo", {
foo: "something"
});
var foo = new context.Foo(); // обращаемся к конструктору через контекст
foo.foo; // something
extend
:refine("Bar", [Foo], {
bar: "something bar"
});
var bar = new Bar();
bar.foo; // something
bar.bar; // something bar
// или
refine("Bar", ["Foo"], { // Foo как строка, удобно если еще не объявлен конструктор
bar: "something bar"
});
var bar = new Bar();
bar.foo; // something
bar.bar; // something bar
// ==================================
var baz = new refine(["Foo", "Bar"], {
baz: "baz something"
});
baz.foo; // something
baz.bar; // something bar
baz.baz; // baz something
В данной реализации методы доступа являются кросс-браузерными.
Для реализации методов доступа есть два варианта, это более стандартный способ создания используя имена get/set или более лаконичный с префиксом свойства "get "/"set ".
Давайте попробуем написать небольшой объект имеющий свойство text
с методами доступа:
var demo = new refine(function() {
var _text;
return {
text: {
set: function(value) {
_text = value;
},
get: function() {
return "Ваше текущее значение: " + _text;
}
}
}
});
demo.text; // Ваше текущее значение: undefined
demo.text = "Привет мир!";
demo.text; // Ваше текущее значение: Привет мир!
Способ реализации объекта со свойствами, доступными только для чтения:
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));
// в консоль выведет: {"left":10,"top":20,"right":100,"bottom":200,"width":90,"height":180}
// работа с объектом
console.log(rect.width); // 90
rect.width = 40; // переопределяем свойство
console.log(rect.width); // 90 - переопределить не удалось, значение осталось неизменным
FAQs
Powerful and flexible generator objects with the possibility of inheritance
The npm package refinejs receives a total of 5 weekly downloads. As such, refinejs popularity was classified as not popular.
We found that refinejs demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.