javascript注意点(1)

1.void运算符

ECMAScript 262规范,关于void说明如下:

The void Operator

The production UnaryExpression : void UnaryExpression is evaluated as follows:

  • Let expr be the result of evaluating UnaryExpression.
  • Call GetValue(expr).
  • Return undefined.

NOTE: GetValue must be called even though its value is not used because it may have observable side-effects.

也就是说会执行void后面的表达式,不论表达式的返回值是啥都会返回undefined。

说明:undefined在JavaScript中并不属于保留字/关键字,因此在IE5.5~8中我们可以将其当作变量那样对其赋值,在新版的浏览器中给undefined赋值时无效的,所以保险起见使用void 0来替代undefined

2.值传递和引用传递

js基本类型按值传递,obj为引用传递。但是这个引用传递和普通引用传递有区别,只能修改对象中的属性,而不能修改整个对象。

var obj = {x : 1};
function foo(o) {
    o = 100;
}
foo(obj);
console.log(obj.x); // 仍然是1, obj并未被修改为100.

3.js的变量提升。

在js的预编译阶段会将var声明的变量和function提到function最开始。

ES6中使用let和class声明的变量和类不存在变量提升的现象

以后想到再加。

原文地址:https://www.cnblogs.com/wangwei1314/p/5558727.html