简体   繁体   English

如何在javascript中检测无效属性的使用?

[英]How can I detect use of invalid properties in javascript?

I'm learning Javascript and I wrote the following code: 我正在学习Javascript,我编写了以下代码:

if (mystring.len > 0) {
    // do stuff
}

I accidentally used .len instead of .length . 我不小心使用.len而不是.length To my surprise, no error was raised. 令我惊讶的是,没有出现任何错误。 mystring.len returned undefined and this made the comparison fail but the code kept right on running. mystring.len返回undefined ,这使得比较失败,但代码保持正常运行。 I would prefer an actual error to be raised so I can fix the code. 我宁愿提出一个实际的错误,所以我可以修复代码。 Adding "use strict" didn't help, nor did jslint. 添加“use strict”没有帮助,jslint也没有帮助。

I know there are ways to actively check whether or not a property exists, but that's not what I'm looking for. 我知道有办法积极检查一个属性是否存在,但这不是我想要的。 I want Javascript to tell me when I've made a typo in a property name. 我希望Javascript告诉我什么时候我在一个属性名称中输入了一个拼写错误。

Is there a way to cause Javascript to give an error in this case? 有没有办法导致Javascript在这种情况下给出错误?

Nope - that is how JavaScript works and it's incredibly useful. 不 - 这就是JavaScript的工作方式,它非常有用。 Who is to say that checking len is something that needs fixing? 谁会说检查len是需要修复的东西? Consider: 考虑:

if(mystring.len === undefined) {
   mystring.len = "Test";
}

The best you can do is to simply check that the thing is defined before using it: 您可以做的最好的事情是在使用它之前简单地检查该事物是否已定义:

if(mystring.len !== undefined) {
}

I appreciate the strangeness, and how it doesn't feel robust (having originally come from a C# background) but there isn't a lot you can do unfortunately. 我很欣赏这种陌生感,以及它是如何感觉不健全的(最初来自C#背景),但不幸的是你没有很多东西可以做。 The fact that JavaScript is case sensitive makes this even more frustrating. JavaScript区分大小写的事实使得这更令人沮丧。 You will learn to live with it though! 你会学会和它一起生活!

If you really really wanted to run some static analysis then you could considering creating a transpiler (eg Babel) extension to run this sort of analysis - but it would get really difficult if you ever expected something to be undefined which I find is common place. 如果你真的真的想要运行一些静态分析,那么你可以考虑创建一个转换器(例如Babel)扩展来运行这种分析 - 但是如果你曾经期望某些东西是undefined ,那么我会觉得这很常见。

edit 编辑

Here's a real example that I'd use where undefined is useful. 这是一个真实的例子,我将使用undefined非常有用。 I'm working with a library that needs to move stuff from one location to another. 我正在使用一个需要将东西从一个位置移动到另一个位置的库。 It can't do that unless the original location has been specified, so I might write something like the following, initializing values if I don't have them for some reason: 除非已经指定了原始位置,否则它不能这样做,因此我可能会编写如下内容,如果由于某些原因我没有它们,则初始化值:

function update(node) {
   if(node.x === undefined) { node.x = 0; }    
   node.y = node.y || 0; // This is the shorthand way I'd actually write it

   // Do some other stuff
};

"use strict" (in my experience) is used so that variables that aren't explicitly declared/instantiated that are then referenced will throw errors (else, JS would just make a new var on the fly). 使用“use strict”(根据我的经验),以便未被显式声明/实例化的变量然后被引用将抛出错误(否则,JS将动态地创建一个新的var)。 So that wouldn't help here. 所以这在这里没有用。

This sounds like an error that would typically be picked up by a compiler in other languages, but since JS is interpreted, you won't have that kind of explicit error checking unless you're in a beefy IDE. 这听起来像是一个错误,通常由其他语言的编译器拾取,但由于JS被解释,除非你在一个强大的IDE中,否则你不会有那种显式的错误检查。 Are you using a text editor or something to write JS? 你使用文本编辑器还是写JS的东西?

Thats not the way JavaScript considers your above code. 这不是JavaScript认为您的上述代码的方式。 Every variable in JS is an object. JS中的每个变量都是一个对象。 So, when you do mystring.len , its actually trying to access the len property of mystring obj and when it doesn't find that property, it will return undefined - which is how it should be. 所以,当你执行mystring.len ,它实际上试图访问mystring obj的len属性,当它找不到该属性时,它将返回undefined - 这应该是怎么回事。 Thats why you will not be able to find any error using JSLint. 这就是为什么你不能使用JSLint找到任何错误。

Just to give you an example - 只是举个例子 -

var myObj = {name: 'Hello', id: 1};
console.log(myObj.name);   // Returns 'Hello'
console.log(myObj.text);   // 'undefined'

In order to prevent such code from giving you any errors, you can easily use the hasOwnProperty() method like follows- 为了防止此类代码给您任何错误,您可以轻松使用hasOwnProperty()方法,如下所示 -

if(myObj.hasOwnProperty('text')) doSomething();

Since myObj doesn't have any property text , the doSomething() function will never be called. 由于myObj没有任何属性text ,因此永远不会调用doSomething()函数。

This is the behaviour of JavaScript as mentioned by many/all answers. 这是许多/所有答案中提到的JavaScript的行为。 However there is an option to prevent new properties you might want to try: 但是,可以选择阻止您尝试的新属性:

Object.seal https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal Object.seal https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal

The simple answer is JavaScript is not ment to be typesafe...You shouldn't check it, but if you still want to check you can do it by: 简单的答案是JavaScript不是类型安全的......你不应该检查它,但如果你仍然想检查你可以通过以下方式来做:

if ('len' in mystring){
}

You should look into Typescript if you ask this question... 如果你问这个问题,你应该看看Typescript ......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM