首页 > 代码库 > C++程序员的javascript教程

C++程序员的javascript教程

本文主要目的是向c++程序员阐述javascript的编程思想,以及编程中的误区。

 

变量声明:

1、变量声明的解析早于代码运行。JavaScript引擎的工作方式是,先解析代码,获取所有被声明的变量,然后再一行一行地运行(This behaviour is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.)

2、给一个未声明的变量赋值等于创建一个全局变量

具体参见:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

http://www.nowamagic.net/librarys/veda/detail/1623

 

变量没有块作用域,只有函数作用域:

1、当初为了实现简单,只有function scope and not block scope,所以{}对变量作用域没起作用

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Statements?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FStatements#Block_Statement

http://stackoverflow.com/questions/17311693/why-does-javascript-not-have-block-scope

var x = 1;
{
  var x = 2;
}
alert(x); // outputs 2

 

布尔条件判断:

除了以下值是假的,其他都是真的

  • false
  • undefined
  • null
  • 0
  • NaN
  • the empty string ("")

例如,下面这个是假的:

var b = new Boolean(false);
if (b) // this condition evaluates to true

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Statements?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FStatements#if...else_Statement

 

闭包:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

 

一些特殊的函数:

bind apply call

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Function/bind