javascript – “use strict”是否适用于在严格范围内声明的函数?
作者:互联网
我在jshint中得到这个,
[L16:C13] W034: Unnecessary directive “use strict”.
不过我的问题是做这样的工作..
function () {
"use strict";
var a = function () {
//stuff, (is this also 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,ecmascript-5 来源: https://codeday.me/bug/20190825/1717747.html