Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

javascript - Strict Violation using this keyword and revealing module pattern

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JSHint has an option called validthis, which:

[...] 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...