Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

内存管理与内存泄漏思考题 #7

Open
FE-Sadhu opened this issue Apr 21, 2019 · 0 comments
Open

内存管理与内存泄漏思考题 #7

FE-Sadhu opened this issue Apr 21, 2019 · 0 comments
Labels
深入js笔记 about javascript

Comments

@FE-Sadhu
Copy link
Owner

1、

var a = 20;
var b = a;
b = 30;

// 这时a的值是多少?

20

2、

var a = { name: '前端开发' }
var b = a;
b.name = '进阶';

// 这时a.name的值是多少

"进阶"

3、

var a = { name: '前端开发' }
var b = a;
a = null;

// 这时b的值是多少

{ name: '前端开发' }

4、

var a = {n: 1};
var b = a;
a.x = a = {n: 2};

a.x 	// 这时 a.x 的值是多少
b.x 	// 这时 b.x 的值是多少

解析:

关键在a.x = a = {n: 2};。.运算符高于=运算符。所以js引擎先执行a.x,因为此时a = {n : 1},所以a.x为undefined并且a和b此时等于都指向的是{n:1,x:undefined}。

执行了.运算符后开始执行=运算符,js是从右到左,所以先把{n:2}的引用给a,此刻:

a: {n: 2},
b: {
    n: 1,
    x: undefined
}

再把引用值a赋给a.x(因为a.x的.运算符已经运算过了,所以这里的a.x可以理解为就是一个普通的标识符,并且这标识符原本的值是undefined),就等于把{n: 2}的引用赋值给了这个标识符。此时:

b: {
   n: 1,
   x: {
       n: 2
   }
},
a: {
    n: 2
}

所以此时

console.log(a.x); // undefined
console.log(b.x); // {n: 2}

5、

从内存来看 null 和 undefined 本质的区别是什么?

  1. 值 null 是一个字面量,它不像undefined 是全局对象的一个属性。
  2. null值表示一个空对象指针,指示变量未指向任何对象,理解为尚未创建的对象比较好理解。undefined表示"缺少值",就是此处应该有一个值,但是还没有定义。

根据用途来理解第二点:

对于null:

(1)作为函数的参数,表示该函数的参数不是对象。(bind的柯里化使用)

(2)作为对象原型链的终点。Object.getPrototypeOf(Object.prototype) // null

(3)如果定义的变量在将来用于保存对象,那么最好将该变量初始化为null,而不是其他值。

(4)当一个数据不再需要使用时,我们最好通过将其值设置为null来释放其引用,这个做法叫做解除引用。(解除引用的真正作用是让值脱离执行环境)

对于undefined:

(1)变量被声明了,但没有赋值时,就等于undefined。

(2)调用函数时,应该提供的参数没有提供,该参数等于undefin ed。

(3)对象没有赋值的属性,该属性的值为undefined。

(4)函数没有返回值时,默认返回undefined。

var i;
i // undefined

function f(x){console.log(x)}
f() // undefined

var  o = new Object();
o.p // undefined

var x = f();
x // undefined

注意:

  1. typeof null // Object 历史遗留问题。
  2. null == undefined // true undefiend其实派生与null。
  3. 对于尚未声明过的变量,我们只能执行一项操作,即使用typeof操作符检测其数据类型,使用其他的操作都会报错。(如var i 的 i)
@FE-Sadhu FE-Sadhu added the 深入js笔记 about javascript label Apr 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
深入js笔记 about javascript
Projects
None yet
Development

No branches or pull requests

1 participant