0

I am using a script that was written in 2006 and rewriting it so that it follows best practices, and for future inclusion into a side project. I use JSHint.com to figure things out and search SO for solutions to other problems it finds. However, I am unable to resolve JSHint's "Do not use 'with'" error. Here is the code:

DragResize.prototype.select = function (newElement) {

    with(this) {
        // Selects an element for dragging.
        if (!document.getElementById || !enabled) return;

        // Activate and record our new dragging element.
        if (newElement && (newElement != element) && enabled) {
            element = newElement;

            // Elevate it and give it resize handles.
            element.style.zIndex = ++zIndex;
            if (this.resizeHandleSet) this.resizeHandleSet(element, true);

            // Record element attributes for mouseMove().
            elmX = parseInt(element.style.left);
            elmY = parseInt(element.style.top);
            elmW = element.offsetWidth;
            elmH = element.offsetHeight;
            if (ondragfocus) this.ondragfocus();
        }
    }

};

The only explanation I have managed to find is the one here: http://jslinterrors.com/unexpected-with, but I do not know how to apply it to the above code. Any help?

NetOperator Wibby
  • 1,354
  • 5
  • 22
  • 44

1 Answers1

0

That code is a brilliant example of why the with statement is so horrible to work with! To resolve the JSHint warning you need to know which of the identifiers referred to in the body of the with statement are actually properties of the DragResize instance (this) and which are actually references to variables in outer scopes.

If, for example, element is a property of the instance, you need to prefix those references with this:

DragResize.prototype.select = function (newElement) {

    if (!document.getElementById || !enabled) return;

    if (newElement && (newElement != element) && enabled) {
        this.element = newElement;
//      ^ prefix instance properties with reference to the instance

        this.element.style.zIndex = ++zIndex;
        if (this.resizeHandleSet) this.resizeHandleSet(element, true);

        // ...

    }
};
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • I have tried this on many other configurations, but nothing's working. There are about 7 more `with(this)` statements too. Should I post a link to the entire script? – NetOperator Wibby Oct 21 '13 at 14:55