JavaScript:防止无意中创建新属性

tim*_*tim 5 javascript error-detection

错别字发生了,有时候用JavaScript跟踪它们真的很难.以此为例(想象一下在更多代码之间):

// no error. I would like a warning
document.getElementById('out').innerHtml = "foo";
Run Code Online (Sandbox Code Playgroud)

对于未声明的变量,严格模式有助于:

"use strict";
var myHTML = "foo";
myHtml = "bar"; // -> error
Run Code Online (Sandbox Code Playgroud)

但它不适用于上面的例子.是否有可以捕获这些错误的程序或模式?我尝试过JSLint和JavaScript Lint,但他们没有抓住它.

理想情况下,我希望这仍然可以工作(没有警告):

// should work (without warning)
function MyClass(arg) {
  this.myField = arg;
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ong 1

使用像 WebStorm 这样的 IDE 对检测此类错误有很大帮助。

为了防止意外向对象添加属性,您可以冻结它: https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

使用 ES6,您可以使用代理来检测这些错误: http://www.nczonline.net/blog/2014/04/22/creating-defective-objects-with-es6-proxies/