4

JavaScript高级程序设计读书笔记二:变量与作用域

 3 years ago
source link: https://foofish.net/JavaScript-note-p2.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

原始值与引用值

6种简单数据类型的值都是原始值, 原始值通过变量赋值给另一个变量时,会复制一个出一个新的值,两者相互独立。

let num1 = 5
let num2 = num1
微信截图_20201207010751.png

引用值通过变量赋值给另一个变量时,也会复制一个值,这个值其实是一个指针(引用),该指针指向的还是同一个对象。

let obj1 = new Object()

let obj2 = obj1
微信截图_20201207011052.png

既然是指向同一个引用对象,那么给obj1添加属性,也会作用到obj2身上去。

obj1.name = "zhangsan"

console.log(obj2.name) // zhangsan

函数在传参的过程中,只有一种情况就是按照值传递,这跟变量的赋值是一个样。只不过,对于引用值,传递的值是指针,但指针指向的还是同一个对象。

instanceof

typeof 一般适合用来判断原始值,对于引用值并不使用,因为 null 和 其它对象返回的都是 object,具体是什么类型的对象并不知道。 而判断引用值具体是什么类型对象最好的方法就是用 instanceof 表达式。

console.log(1 instanceof Object)  //false
let obj = new Object();
console.log(obj instanceof Object)  //true
console.log(null instanceof Object)  //false



function fun(){
    //
}
console.log(fun instanceof Object)  //true
console.log(fun instanceof Function) //true

console.log([] instanceof Object) //true
console.log([] instanceof Array) //true

变量的作用范围称为作用域或者执行上下文,变量脱离了该作用域不再可见,所有系统查找一个变量时是有一个作用域链的。先从引用该变量最近的块作用域找,没找到继续往外局部作用域找,再没找到就在全局作用域中查找。如果还没找到就会报错 ReferenceError: xxx is not defined。

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK