JavaScript的类型小记

https://icbd.github.io/wiki/web/2016/10/07/js%E7%B1%BB%E5%9E%8B.htmlhtml

原始类型 && 引用类型

JavaScript中没有可是有类型.
类型分两种--原始类型(string,number,boolean,null,undefined)和引用类型(保存对象的引用).git

原始类型的复制是直接复制,多个副本互不干扰.

var a = 'haha';
var b = a;

a = 'hehe';

console.log(a); //hehe
console.log(b); //haha

引用类型中只保存引用,对象实例只有一份.

var arr = ['haha','hehe'];
var arr2 = arr;
arr.push('heihei');

console.log(arr); //["haha", "hehe", "heihei"]
console.log(arr2); //["haha", "hehe", "heihei"]

解除引用使用null,会触发自动垃圾回收.github

arr = null;

JavaScript还提供了6种内建类型-Object,Array,Function,Date,Error,RegExp.web

内建类型能够用new来实例化,他们也是保存对象引用.this

判断类型

typeof鉴别类型.code

console.log(typeof true);//'boolean'
console.log(typeof '你好!');//'string'
console.log(typeof 2016);//'number'
console.log(typeof undefined);//'undefined'
console.log(typeof null);//'object' 这个是特例,应该用 n === null 来断定


console.log(typeof [1, 2, 3]);//'object'

var obj = {
    name: 'haha',
    age: 123

};
console.log(typeof obj);//'object'

var add = function (a, b) {
    return a + b;
};
console.log(typeof add);//'function'

对于引用类型, 能够用instanceof来断定构造来源.
instanceof可断定继承, 全部对象都是Object的实例.htm

var arr = [1, 2, 3, 4];
console.log(arr instanceof Array); //true
console.log(arr instanceof Object); //true

function Person(name) {
    this.name = name;
}
var xiaoMing = new Person('小明');

console.log(xiaoMing instanceof Person); //true
console.log(xiaoMing instanceof Object); //true

console.log(Person instanceof Function); //true
console.log(Person instanceof Object); //true

灵异现象1

在原始类型上调用方法???对象

var str = "hello world";
console.log(str.toUpperCase());//HELLO WORLD

实际上,js引擎作了些额外工做:继承

var str = "hello world";
var temporary = new String(str);
var _temporary = temporary.toUpperCase();
temporary = null;

console.log(_temporary);

这里的String叫原始封装类型.
这个过程叫自动打包,在原始对象的值被读取的时候进行.ip

console.log(str instanceof String);// false

instanceof 没有涉及到str值的读取,因此不会生成临时对象,str也就不会被断定为String.

灵异现象2

var f = new Boolean(false);
if (f) {
    console.log('it is true.');
} else {
    console.log('it is false.');
}

// 'it is true.'

f在这里是一个Boolean的对象,对象总会判为真.即便他的内容是false.

JavaScript的false只有如下几种:

false
0
""

undefined
null
NaN
相关文章
相关标签/搜索