【问题标题】:Resolve JSHint's "Don't use 'with'" recommendation解决 JSHint 的“不要使用 'with'”建议
【发布时间】:2013-10-20 14:13:12
【问题描述】:

我正在使用 2006 年编写的脚本并对其进行重写,以使其遵循最佳实践,并在未来包含在一个辅助项目中。我使用 JSHint.com 来解决问题并在 SO 中搜索它发现的其他问题的解决方案。但是,我无法解决 JSHint 的“请勿使用 'with'”错误。代码如下:

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();
        }
    }

};

我设法找到的唯一解释是这里的一个:http://jslinterrors.com/unexpected-with,但我不知道如何将其应用于上述代码。有什么帮助吗?

【问题讨论】:

    标签: jquery jslint jshint


    【解决方案1】:

    这段代码很好地说明了为什么with 语句很难使用!要解决 JSHint 警告,您需要知道 with 语句正文中引用的哪些标识符实际上是 DragResize 实例 (this) 的属性,哪些实际上是对外部范围内变量的引用。

    例如,如果element 是实例的属性,则需要在这些引用前加上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);
    
            // ...
    
        }
    };
    

    【讨论】:

    • 我已经在许多其他配置上尝试过这个,但没有任何效果。还有大约 7 个 with(this) 声明。我应该发布整个脚本的链接吗?
    猜你喜欢
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 2018-12-11
    • 2011-01-26
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多