当前位置: 首页 > Web前端 > JavaScript

JavaScript在严格模式下使用了一些变化并影响了

时间:2023-03-26 22:02:43 JavaScript

1.严格模式下不能使用with语法1.严格模式下可执行以下代码constobj={name:'peter'}functionfoo(){with(obj){console.log(name)}}foo()//peter2,当我们开启严格模式时,with语法会直接被禁用2.严格模式下,在函数中使用this会把this指向functionfoo(){console.log(this)//pointstowindow}2、当我们启用严格模式时functionfoo(){console.log(this)//undefined}3、在严格模式下,会防止全局变量1的意外声明。当不使用严格模式时,以下语法是允许的,变量将被定义为全局变量functionfoo(){name="peter"}console.log(name)//peter2.这个变量被命名为严格模式下,不会运行,执行时会报错。4、严格模式下,参数重名的函数将不会运行。1.如果不使用严格模式,我们可以命名一个参数重名的函数functionfoo(a,b,a){console.log(a,b,a)}foo(1,2,3)//1,2,32,开启严格模式后,这种写法会报错:SyntaxError:Duplicateparameternamenotallowedinthiscontext5。在严格模式下,之前的八进制写法会报错1。之前的八进制写法格式constnum=0123console.log(num)//832。在严格模式下,不允许这样写:SyntaxError:Octalliteralsarenotallowedinstrictmode。但是我们可以改成下面的格式"usestrict"constnum=0o123console.log(num)//836,在严格模式下,会导致silence失败的赋值操作抛出错误1。当不使用严格模式时,下面对obj对象中name的修改会失败,但是不会抛出错误constobj={name:'peter'}Object.defineProperty(obj,'name',{writable:false})obj.name='lisa'2.但是当我们启用严格模式时,对name的修改会报错被抛出:TypeError:无法分配给对象'#'的只读属性'name'“使用严格”constobj={name:'peter'}Object.defineProperty(obj,'name',{writable:false})obj.name='lisa'7.严格模式下,eval不会为上层引用变量1.不使用严格模式constjsStr='varmessage="helloworld";console.log(message)'eval(jsStr)//helloworldconsole.log(message)//helloworld2.使用严格模式后:ReferenceError:messageisnotdefined"usestrict"constjsStr='varmessage="helloworld";console.log(message)'eval(jsStr)console.log(message)8.严格模式下,删除不可删除的属性会报错TypeError:Cannotdeleteproperty'name'of#"usestrict"constobj={name:'peter'}Object.defineProperty(obj,'name',{writable:false,configurable:false})deleteobj.name9。以后js要用到的关键字(保留字)不能在严格模式下使用