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
在原始類型上調用方法???對象
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.
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