为什么我发现 Javascript/jQuery 很难正确?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3398220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:03:31  来源:igfitidea点击:

Why am I finding Javascript/jQuery so difficult to get right?

javascriptjquery

提问by JMan

My background is in C and I've picked up PHP, mySQL, HTML, CSS without too much issue.

我的背景是 C 并且我已经学会了 PHP、mySQL、HTML、CSS,没有太多问题。

But I'm finding Javascript/jQuery surprisingly difficult to get right. Very frustrating. Why?

但我发现 Javascript/jQuery 出人意料地难以正确。非常令人沮丧。为什么?

  1. It seems to violate a number of traditional programming principles (e.g. variable scope)

  2. Undefined variables seem to appear out of nowhere and already have values associated with them. For example (from the jQuery docs):

    $("a").click(function(event) {
        event.preventDefault();
        $('<div/>')
              .append('default ' + event.type + ' prevented')
              .appendTo('#log');
    });
    

    What exactly is "event"? Do I have to use this variable name? Should I just assume that this object is magically instantiated with the right stuff and I can use any of the methods list at the JQuery API?

  3. There seems to be bunch of random rules (e.g. return false to stop a default action, but sometimes this doesn't work?)

  4. Non-deterministic behavior when debugging. (e.g. I refresh the browser, try something and get result X for JS variables I'm watching in Firebug. I refresh again and I get result Y?)

  5. Very messy looking code that is hard to follow. What happens when? I'm using Firebug and Chrome Developer Tools, but I'm not getting enough visibility.

  1. 它似乎违反了许多传统的编程原则(例如变量范围)

  2. 未定义的变量似乎无处不在,并且已经有了与之关联的值。例如(来自 jQuery 文档):

    $("a").click(function(event) {
        event.preventDefault();
        $('<div/>')
              .append('default ' + event.type + ' prevented')
              .appendTo('#log');
    });
    

    究竟什么是“事件”?我必须使用这个变量名吗?我应该假设这个对象是用正确的东西神奇地实例化的,我可以使用JQuery API 中的任何方法列表吗?

  3. 似乎有一堆随机规则(例如返回 false 以停止默认操作,但有时这不起作用?)

  4. 调试时的非确定性行为。(例如,我刷新浏览器,尝试一些操作并为我在 Firebug 中查看的 JS 变量获得结果 X。我再次刷新并获得结果 Y?)

  5. 非常凌乱的代码,难以理解。什么时候发生?我正在使用 Firebug 和 Chrome 开发人员工具,但我没有获得足够的可见性。

It seems like everyday there's some random JS "rule" that comes up that I've never seen before in any of my JS books or tutorials.

似乎每天都有一些随机的 JS“规则”出现,这是我以前在我的任何 JS 书籍或教程中从未见过的。

What do I need to do to make Javascript/jQuery more deterministic, controlled, and logical to me?

我需要做什么才能使 Javascript/jQuery 对我来说更具确定性、可控性和逻辑性?

Are there any resources that explain Javascript's quirks/gotchas?

是否有任何资源可以解释 Javascript 的怪癖/陷阱?

Thanks!

谢谢!

采纳答案by Broam

Douglas Crockford's "Javascript: The Good Parts" was an invaluable resource. Javascript plays a lot more like Lua, Lisp, or Python than C, it just happens to LOOK like C.

Douglas Crockford的“ Javascript: The Good Parts”是一份宝贵的资源。与 C 相比,Javascript 更像 Lua、Lisp 或 Python,只是碰巧看起来像 C。

Link provided to Amazon; I snagged mine from O'Reilly.

提供给亚马逊的链接;我从 O'Reilly 那里抢到了我的。

回答by BalusC

1) It seems to violate a number of traditional programming principles (e.g. variable scope)

1) 它似乎违反了一些传统的编程原则(例如变量作用域)

You need to declare variables using var, else it will go into the global scope.

您需要使用 声明变量var,否则它将进入全局范围。

2) Undefined variables seem to appear out of nowhere and already have values associated with them (how did this happen?)

2)未定义的变量似乎无处不在,并且已经有与之关联的值(这是怎么发生的?)

This is possibly related to 1) and/or 4).

这可能与 1) 和/或 4) 有关。

3) There seems to be bunch of random rules (e.g. return false to stop a default action, but sometimes this doesn't work?)

3)似乎有一堆随机规则(例如,返回 false 以停止默认操作,但有时这不起作用?)

You need to let the handler return false as well. E.g. form onsubmit="return functionname()". You also need to return from the "main" function, not only from a closure (a function inside a function), referring to your previous question. It would only return into the "main" function and continue on.

您还需要让处理程序返回 false。例如form onsubmit="return functionname()"。您还需要从“main”函数返回,而不仅仅是从闭包(函数内的函数)返回,参考您之前的问题。它只会返回到“main”函数并继续。

4) Non-deterministic behavior when debugging. (e.g. I refresh the browser, try something and get result X for JS variables I'm watching in Firebug. I refresh again and I get result Y?)

4) 调试时的非确定性行为。(例如,我刷新浏览器,尝试一些操作并为我在 Firebug 中查看的 JS 变量获得结果 X。我再次刷新并获得结果 Y?)

Probably the code was executed before the HTML DOM was finished populating. You need to hook on window.onloador $(document).ready()whenever you want to execute stuff during page load.

代码可能是在 HTML DOM 完成填充之前执行的。在页面加载期间,您需要挂钩window.onload$(document).ready()随时执行内容。

5) Very messy looking code that is hard to follow. What happens when? I'm using Firebug and Chrome Developer Tools, but I'm not getting enough visibility.

5) 看起来非常凌乱的代码,难以理解。什么时候发生?我正在使用 Firebug 和 Chrome 开发人员工具,但我没有获得足够的可见性。

I bet that you're talking about jQuery source? It's just a large library. You should after all not worry about this when debugging. Rather worry about your own code. However, make sure that you're looking at the unminified version of jQuery's source code.

我敢打赌你说的是 jQuery 源代码?这只是一个大图书馆。毕竟在调试时你不应该担心这个。而是担心您自己的代码。但是,请确保您查看的是未缩小版本的 jQuery 源代码。



See also:

也可以看看:

回答by TCCV

To be honest, I think you have a good understanding. Some of my hangups were similar. The way that I have been moving on is "well, if that's the way it is, then that's the way it is". Just accept the idiosyncrasies and plow forward. PHP does some of the same things (variables can show up out of nowhere, etc...). Just code the way you want to code and if it works, then great!

老实说,我认为你有一个很好的理解。我的一些挂断是相似的。我一直在前进的方式是“好吧,如果是这样,那么就是这样”。只需接受特质并继续前进。PHP 做了一些相同的事情(变量可能会突然出现,等等......)。只需按照您想要的方式进行编码,如果有效,那就太好了!

Then after you get to that point start breaking out the profiler and see if there's anything that you can optimize.

然后在你到达那个点之后开始打破分析器,看看是否有任何可以优化的东西。

Here are a couple of things:

这里有几件事:

If you understand CSS, then jQuery selectors should be easy. As far as the code goes, that's straightforward too if you can deal with chainingand JSON. EDIT: also, the jQuery documentationon everything is EXCELLENT! And There is no shortage of jQuery experts here on SO to help us noobs (and hopefully we can return the favor for newer noobs).

如果您了解 CSS,那么 jQuery 选择器应该很容易。就代码而言,如果您可以处理链接和 JSON ,那也很简单。编辑:此外,关于所有内容的jQuery 文档都非常好!并且这里不乏 jQuery 专家来帮助我们菜鸟(希望我们可以回报新菜鸟的青睐)。

There is a scope to work with. (Basically) anything written outside of a function or object is in global scope. If you are inside of an object or function and use varthen that sets the variable's scope

有一个工作范围。(基本上)在函数或对象之外编写的任何内容都在全局范围内。如果您在对象或函数内部并使用,var则设置变量的范围

Javascript isn't like a C-based language (C++ or PHP even). It uses prototypes to deal with class/object relationships rather than a subclassing scheme.

Javascript 不像基于 C 的语言(甚至 C++ 或 PHP)。它使用原型来处理类/对象关系而不是子类化方案。

The #1 thing that threw me for a loop is that any JS that appears anywhere on the page or that was included in <script>tags is fair game. If you have a global variable in one script, you can use that same variable in a completely different script and it will work. That may be what you mean about variables showing up out of nowhere. Also, there are some DOM based variables that can just "show up" too.

让我循环的第一件事是,任何出现在页面上任何位置或包含在<script>标签中的JS都是公平的游戏。如果你在一个脚本中有一个全局变量,你可以在一个完全不同的脚本中使用相同的变量,它会起作用。这可能就是你所说的突然出现的变量的意思。此外,还有一些基于 DOM 的变量也可以“显示”。

Anyways, I think that if you just plow ahead, you'll get some "AHA" moments. I'm a relative noob to programming, but I continually grow as long as I don't hang up on something that doesn't have too much of an impact on actually making the code run.

无论如何,我认为如果你继续努力,你会得到一些“AHA”时刻。我是编程的相对菜鸟,但只要我不挂断对实际运行代码没有太大影响的东西,我就会不断成长。

回答by meder omuraliev

  1. It's a language based on prototypal inheritance and is influenced by functional programming languages and the paradigm so it isn't completely just OO/Procedural like other languages. Variables are implied globals unless declared with var.

  2. Please include an example?

  3. return falseexits out of the function as with any language's return statement. preventDefault()would be the DOM method to cancel the default behaviour of a link

  4. Javascript is used primarily on the client side. Since there are many user agents, each of them have a different implementation of the DOM, which is very inconsistent, moreso than JS itself. Again, please include a real example to get a definitive answer.

  5. You'll find messy looking code in any language, and maybe your lack of understanding perceives the code as messy, when in fact it isn't so bad. Or maybe you're looking at some minified/obfuscated code.

  1. 它是一种基于原型继承的语言,受函数式编程语言和范式的影响,因此它不像其他语言那样完全只是面向对象/过程。变量是隐含的全局变量,除非用 声明var

  2. 请举例说明?

  3. return false与任何语言的 return 语句一样退出函数。preventDefault()将是取消链接默认行为的 DOM 方法

  4. Javascript 主要用于客户端。由于有很多用户代理,每个代理都有不同的 DOM 实现,这非常不一致,比 JS 本身更不一致。再次,请提供一个真实的例子以获得明确的答案。

  5. 你会发现任何语言的代码看起来很乱,也许你缺乏理解会认为代码很乱,但实际上它并没有那么糟糕。或者,您可能正在查看一些缩小/混淆的代码。

I recommend http://eloquentjavascript.net/for learning aspects of Javascript.

我推荐http://eloquentjavascript.net/来学习 Javascript 的各个方面。

Things you'll learn from the link above

你将从上面的链接中学到的东西

  • lambdas
  • closures
  • Prototypal inheritance
  • Event based programming
  • Debugging
  • DOM
  • 拉姆达
  • 关闭
  • 原型继承
  • 基于事件的编程
  • 调试
  • DOM

回答by brad

Crockford's "Javascript: The Good Parts" gives some common JS patterns that help with variable privatization and scoping. This is for javascript in general. For jQuery I just use the API. Also the Yui Theatre videos on javascript are quite good

Crockford 的“ Javascript: The Good Parts”给出了一些有助于变量私有化和范围界定的常见 JS 模式。这通常适用于 javascript。对于 jQuery,我只使用 API。javascript 上的 Yui Theatre 视频也很不错

回答by Ken Struys

Javascript can be a little tricky and some of it's functional aspects confuses people. If you actually learn and understand the language you'll find it really useful, most people just randomly start using it and then just hate.

Javascript 可能有点棘手,它的一些功能方面让人们感到困惑。如果你真的学习并理解了这门语言,你会发现它真的很有用,大多数人只是随机开始使用它,然后就讨厌它。

Read javascript the good parts by crockford, it's really helpful: http://javascript.crockford.com/

阅读 crockford 的 javascript 好部分,它真的很有帮助:http://javascript.crockford.com/

Also make sure you understand closure. It's a fundamental that people don't get but often use.

还要确保您了解闭包。这是人们没有得到但经常使用的基础知识。

回答by Jakob

"JavaScript: The Good Parts" by Douglas Crockford is a good start

Douglas Crockford 的“JavaScript: The Good Parts”是一个好的开始

In your case, the appendices ("the bad parts" and "the awful parts") might be the most interesting :)

在你的情况下,附录(“坏的部分”和“糟糕的部分”)可能是最有趣的:)

回答by Bob Gregor

In terms of variable scope, there are local and global variables. One of the gotchyas of variable scope can be seen in this example:

就变量作用域而言,有局部变量和全局变量。在这个例子中可以看到变量范围的问题之一:

var thisIsAGlobalVariable
function anon () { 
   var thisIsALocalVariable
   thisIsAGlobalVariable = 5; //if you don't use the var prefix inside a fn, it becomes global
}

回答by Nealv

You are finding it difficult because:

您觉得这很困难,因为:

  • javascript has another kind of syntax.
  • javascript is dificult to debug
  • javascript has no autocompletion like c# etc) ?or does it
  • javascript has illogical rules (they become logical once you are known with them)
  • everything can be done in 1000 ways, and when you search for a solution, you will find 2000 answers :) where c#, php mostly have a good practice function u "should/could" use
  • javascript 有另一种语法。
  • javascript 很难调试
  • javascript 没有像 c# 等那样的自动完成功能?或者有吗?
  • javascript 有不合逻辑的规则(一旦你了解它们,它们就会变得合乎逻辑)
  • 一切都可以用 1000 种方式完成,当您搜索解决方案时,您会找到 2000 个答案:) 其中,c#、php 大多具有您“应该/可以”使用的良好实践功能

However, I started using js/jquery a half year ago, with the same reasoning as you do, and I stuck to it, and now I use it daily to enhance my webapps.

然而,我半年前开始使用 js/jquery,和你一样,我坚持使用它,现在我每天都使用它来增强我的 web 应用程序。

I just love it (especcially jquery). It is a life saver, I know what and where to look, I can do about anything with it.

我只是喜欢它(尤其是 jquery)。它是一个救生员,我知道该看什么和看哪里,我可以用它做任何事情。

Everything seems logical.

一切似乎都合乎逻辑。

If I can give you one advice: javascript/jquery is a sour apple, but just hang in there, bit trough and you won't regret it.

如果我能给你一个建议:javascript/jquery 是一个酸苹果,但只要坚持下去,有点低谷,你不会后悔的。

also, a loooot of people use it and are always willing to lend a hand if needed (I know I do)

此外,很多人都在使用它,并且在需要时总是愿意伸出援手(我知道我愿意)

回答by Frank Schwieterman

Javascript is tricky. You don't have a compiler watching your back. To compensate, unit testing becomes more important. I've been doing my unit testing with jQuery/QUnit, but I recently started using Jasmine (http://github.com/pivotal/jasmine) and I recommend it 200%. Its a great testing framework.

Javascript 很棘手。你没有一个编译器看着你。作为补偿,单元测试变得更加重要。我一直在用 jQuery/QUnit 进行单元测试,但我最近开始使用 Jasmine ( http://github.com/pivotal/jasmine),我 200% 推荐它。它是一个很棒的测试框架。

If you're not familiar with testing, or testing with javascript, I'd highly recommend finding unit tests for other OSS javascript projects (hopefully for code you could use) and seeing how they test it.

如果您不熟悉测试或使用 javascript 进行测试,我强烈建议您查找其他 OSS javascript 项目的单元测试(希望您可以使用代码)并查看他们如何测试它。

With unit tests, you'll make the same mistakes, but catch them much sooner and with less grief. And if your tests are good, the mistakes won't come back after you fix tham.

使用单元测试,你会犯同样的错误,但能更快地发现它们,而且不会那么痛苦。如果你的测试很好,那么在你修复 tham 之后错误就不会再回来了。