严格违规使用此关键字并显示模块模式 [英] Strict Violation using this keyword and revealing module pattern

查看:129
本文介绍了严格违规使用此关键字并显示模块模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法获得以下内容以传递jslint / jshint

Having trouble getting the following to pass jslint/jshint

/*jshint strict: true */
var myModule = (function() {
    "use strict";

    var privVar = true,
        pubVar = false;

    function privFn() {
        return this.test; // -> Strict violation.
    }

    function pubFn() {
        this.test = 'public'; // -> Strict violation.
        privFn.call(this); // -> Strict violation.
    }

    return {
        pubVar: pubVar,
        pubFn: pubFn
    };

}());

myModule.pubFn();

据我所知,这是因为使用这个在一个函数声明中,但我读到了Crockford写的东西,他说违规是为了防止全局变量污染 - 但这里唯一的全局变量是我明确定义的那个...... myModule 。其他所有东西都保存在直接的功能范围内,我应该可以使用这个来引用该模块。

I understand it's being caused by the use of this in a function declaration, but I read something Crockford wrote and he said the violation is meant to prevent global variable pollution - but the only global variable here is the one I'm explicitly defining... myModule. Everything else is held in the immediate function scope, and I should be able to use this to refer to the module.

任何想法如何让这个模式通过?

Any ideas how I can get this pattern to pass?

更新:如果我使用函数表达式而不是声明,这似乎工作,即

Update: if I use a function expression instead of a declaration, this seems to work, ie

var pubFn = function () { ...

我不是这种格式的粉丝,更喜欢将函数名称和命名参数更接近并且声明看起来/感觉更清晰。老实说,我不明白为什么会抛出违规行为 - 这种模式没有理由。

I'm not a fan of this format though, prefer to have the function name and named params closer and the declaration looks/feels cleaner. I honestly don't see why this is throwing the violation - there's no reason for it in this pattern.

推荐答案

JSHint有一个选项名为 validthis ,其中:

JSHint has an option called validthis, which:


[...]在代码以严格模式运行并且使用 this时,禁止警告有关可能的严格违规行为在非构造函数[...]中,如果您肯定使用在严格模式下有效。

[...] suppresses warnings about possible strict violations when the code is running in strict mode and you use this in a non-constructor function [...], when you are positive that your use of this is valid in strict mode.

在JSHint抱怨的函数中使用它,在你的情况下,看起来像这样:

Use it in the function that JSHint is complaining about, which in your case, would look like this:

function privFn() {
    /*jshint validthis: true */
    return this.test; // -> No Strict violation!
}

function pubFn() {
    /*jshint validthis: true */
    this.test = 'public'; // -> No Strict violation!
    privFn.call(this); // -> No Strict violation!
}

在每个函数中指定它可能看起来很痛苦适用,但如果您在模块功能的顶部设置选项,则可能会隐藏正版严格模式违规行为。

It might seem like a pain to have to specify that in each function where it applies, but if you set the option at the top of your module function, you may hide genuine strict mode violations from yourself.

这篇关于严格违规使用此关键字并显示模块模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆