gpt4 book ai didi

javascript - "use strict"是否适用于在严格范围内声明的函数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:48:33 24 4
gpt4 key购买 nike

我在 jshint 中得到这个,

[L16:C13] W034: Unnecessary directive "use strict".

但是我的问题是做这样的事情..

function () {
"use strict";

var a = function () {
//stuff, (is this also strict)
}

}

stuff 也会严格吗?显然,严格声明之外的内容不会是严格的。但是里面的其他函数是从非严格开始还是继承严格?

最佳答案

是的,会很严格;并且,严格性是继承的。

"use strict"; 的任何子范围也将是严格的。 没有必要如果你能声明一个封装范围严格的话,我可以看到声明每个函数strict

我尝试在范围内和范围外调用该函数,以确保它不会产生影响。这是使用 mocha

运行的测试
var assert = require('assert');

var inside = function () {
"use strict";
var a = inside.a = function () {
bar = 1;
return bar;
};
var b = inside.b = function () {
var bar = 1;
return bar;
};
var c = inside.c = function () {
"use strict";
bar = 1;
return bar;
};
var d = inside.d = function () {
"use strict";
var bar = 1;
return bar;
};

describe('Inside Context', function () {
it('inside a (no strict, no var)', a )
it('inside b (no strict, var)', b )
it('inside c (strict, no var)', c )
it('inside d (strict, var)', d )
} );

};

inside();

describe('Outside Context', function () {
it('outside a (no strict, no var)', inside.a )
it('outside b (no strict, var)', inside.b )
it('outside c (strict, no var)', inside.c )
it('outside d (strict, var)', inside.d )
} );

在这里我们看到,在内部和外部都没有用 var 声明变量,我们有一个测试失败,表明 strict 正在工作:

Inside Context
1) inside a (no strict, no var) // fail
✓ inside b (no strict, var)
2) inside c (strict, no var) // fail
✓ inside d (strict, var)

Outside Context
3) outside a (no strict, no var) // fail
✓ outside b (no strict, var)
4) outside c (strict, no var) // fail
✓ outside d (strict, var)

关于javascript - "use strict"是否适用于在严格范围内声明的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20807336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com