是否"使用严格"在文件的第一行影响文件中的所有函数?

时间:2015-08-18 10:22:02

标签: typescript tslint

所以我将此代码改编自here用于学习目的:

"use strict";
/// <reference path="./definitelyTyped/node/node.d.ts" />
import * as net from "net";

let sockets: net.Socket[] = [];

/*
 * Cleans the input of carriage return, newline
 */
function cleanInput(data: Buffer): string {
    return data.toString().replace(/(\r\n|\n|\r)/gm, "");
}

/*
 * Method executed when data is received from a socket
 */
function receiveData(socket: net.Socket, data: Buffer): void {
    let cleanData: string = cleanInput(data);
    if (cleanData === "@quit") {
        socket.end("Goodbye!\r\n");
    } else {
        for (var i: number = 0; i < sockets.length; i++) {
            if (sockets[i] !== socket) {
                sockets[i].write(data);
            }
        }
    }
}

/*
 * Method executed when a socket ends
 */
function closeSocket(socket: net.Socket): void {
    let i: number = sockets.indexOf(socket);
    if (i !== -1) {
        sockets.splice(i, 1);
    }
}

/*
 * Callback method executed when a new TCP socket is opened.
 */
function newSocket(socket: net.Socket): void {
    sockets.push(socket);
    socket.write("Welcome to the Telnet server!\r\n");
    socket.on("data", function(data: Buffer): void {
        receiveData(socket, data);
    });
    socket.on("end", function(): void {
        closeSocket(socket);
    });
}

// create a new server and provide a callback for when a connection occurs
let server: net.Server = net.createServer(newSocket);

// listen on port 4444
server.listen(4444);
console.log("started");

我使用这些tslint规则在此文件上运行tslint.json

这就是我得到的:

  

app.ts [10,1]:缺少&#39;使用严格的&#39;

     

app.ts [17,1]:缺少&#39;使用严格的&#39;

     

app.ts [33,1]:缺少&#39;使用严格的&#39;

     

app.ts [43,1]:缺少&#39;使用严格的&#39;

我的理解是,文件第一行的"use string";应该是整个文件的全局。然而,每个函数都会产生一个消息。我错过了什么吗?

2 个答案:

答案 0 :(得分:2)

  

我的理解是,&#34;使用字符串&#34 ;;在文件的第一行应该是整个文件的全局。然而,每个函数都会产生一条消息

您的理解是正确的。但是,您请求tslint以确保所有函数以及"check-function" set to true。将其设置为false,因为如果您已启用模块级别,则不需要它。

答案 1 :(得分:1)

可以在全局范围或单个函数中启用严格模式:

// Enable strict mode globally
"use strict";
var v = "This script is in strict mode.";

或在当地:

function strict() {
  'use strict';

  function nested() {
    return "Nested function is also in strict mode.";
  }

  return "Function is in strict mode. " + nested();
}

function notStrict() {
  return "This function is not in strict mode.";
}