A
A
Andrew2017-05-17 09:45:41
JavaScript
Andrew, 2017-05-17 09:45:41

Why do you need a decorator?

I read a little about it, but I didn’t understand the whole point well, they write - the decorator can change the behavior of the object on the fly, which means that if we defined the Circle constructor function with one draw method, then after creating the object we will have only one method, but if we still have, for example you need the behavior from the clear object - to clear the drawn, and that when creating the object in the FK the clear method was not defined, then in this situation it would be good to use a decorator? JS allows you to change the FK prototype and immediately all already created objects will receive changes, for which the decorator can change the FK.

function Circle() {}
Circle.prototype.draw = function () { return 'drawing' }
var circle1 = new Circle();
circle1.draw() // "drawing"
circle1.clear() // is not a function
Circle.prototype.clear = function () { return 'clearing' }
circle1.clear() // "clearing"

above, the behavior of the object changes after the creation of the object itself, does the decorator solve this problem? if not, can you tell what it is for, and a simple example

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Luzanov, 2017-05-17
@dmitry_luzanov

https://learn.javascript.ru/decorators

A
Andrew, 2017-05-22
@undefined_title

js example. I wrote for myself, I have not yet checked with other sources how much this is the "correct decorator"

testDecorator = function(func1, func2) { return function(a, b) { return func1( func2(a, b) ) } }
func1 = a => return a * a
func2 = (a, b) => { return a + b }
countSome = testDecorator(func1, func2)
countSome(2, 2); // 16
countSome(2, 3); // 25

I want to see comments about this decorator

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question