0

I would like to create an utility object/function size, which given a dom element myDom and calling another function as big or small change the inline style of myDom.

Currently I am interesting in a solution for actually passing myDom to function big or small so there the inline style modification can happen.

I would like to know which JS pattern could help me to achieve this result and a brief example.

window.size(myDom).big();

window.size(myDom).small();

3 Answers 3

2

You can just return object with big and small methods and use closure to access myDom:

function size(myDom) {
    return {
        big: () => { myDom.style.... }
        small: () => { .... }
    };
}

Or you can create class with myDom as constructor parameter (which stores it in the field) and appropriate methods.

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to use ES6 classes, you could return an instance of a class that wraps around your element:

class Sizeable {
    constructor(el) {
        this.el = el;
    }

    big() {
        // do something with this.el
    }

    small() {
        // do something with this.el
    }
}

window.size = function(el) {
    return new Sizeable(el);
};

Which is, of course, roughly equivalent to:

function Sizeable(el) {
    this.el = el;
}

Sizeable.prototype.big = function() {
    // do something with this.el
}

Sizeable.prototype.small = function() {
    // do something with this.el
}

window.size = function(el) {
    return new Sizeable(el);
};

Comments

0

The size method must have an object as its return value.

That object must have properties named big and small.

It should also have any additional data (stored in other properties) that you want to make available to

The values of each of those properties must be functions.

Those functions can either read variables from the function which created them (as closures) or use the this keyword to read the data from the object (you would need to store the data on that object in other properties).

1 Comment

could you please provide me an example of code (myDom is a dom element can I add there big/small)? it would really help me. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.