Motive behind strict mode syntax error when deleting an unqualified identifier?

試著忘記壹切 提交于 2019-11-30 01:16:18
user123444555621

You are talking about Section 11.4.1, paragraph 5.a. of the specs:

  1. Else, ref is a Reference to an Environment Record binding, so
    a. If IsStrictReference(ref) is true, throw a SyntaxError exception.
    b. Let bindings be GetBase(ref).
    c. Return the result of calling the DeleteBinding concrete method of bindings, providing GetReferencedName(ref) as the argument.

What you called "unqualified identifiers" is officially named "Environment Record binding".

Now, to your question. Why throw a SyntaxError when 5.c. would fail anyway? I think you answered it yourself!

Strict mode must do a runtime check here, because a TypeError is thrown when this is encountered.

That's right. But it's always better to fail fast. So, when there is a chance of detecting a SyntaxError (at parse time), that opportunity should be taken.

Why? It saves you the trouble of fixing your app if an error occurs. Think about IDEs that may show you the error right away, as opposed to hours of debugging.
Also, such restrictions may be advantageous for optimized JIT compilers.

If you want to delete object in strict mode. You have to explicitly mention about the property access. Also note that, how you call the function is important. If new operator isn't used this is undefined under use strict, and you cant use the below method. Example:

'use strict'
function func(){
  var self = this;
  self.obj = {};
  self.obj.x = 'y'

  console.log(self.obj);
  delete self.obj // works
  // delete obj // doesn't work
  console.log(self.obj);
}

var f = new func();

For deleting object outside of the function(closure), you will have to call like

// same code as above
delete f.obj
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!