一丶JavaScript 类型

115 阅读2分钟
一、内置类型

JavaScript 有 7 中内置类型:

  • null 空值
  • undefined 未定义
  • boolean 布尔值
  • number 数字
  • string 字符串
  • symbol 符号(ES6 中新增)
  • object 对象
二、拓展
  • typeof 查看值的类型,返回类型的字符串值
typeof undefined === 'undefined' // true
typeof true === 'boolean' // true
typeof 22 === 'number' // true
typeof '22' === 'string' // true
typeof {} === 'object' // true

// ES6 中新增类型
typeof Symbol() === 'symbol' // true

// null 比较特殊
typeof null === 'object' // true

// 我们可以使用复合条件来检测null值的类型
var a = null;
(!a && typeof a ==='object'); // true

// 还有一种特殊情况
// function(函数)是JavaScript的一个内置类型,它是object的一个子类型
typeof function(){} === 'function' // true

// 函数是“可调用对象”,有一个内部属性[[call]],该属性使其可以被调用
// 函数不仅是对象,还可以拥有属性。
function testFun(a,b){}
// 函数对象的 length 属性是其声明的参数的个数
testFun.length; // 2
  • instanceof 测试一个构造函数的prototype属性是否出现在另一个对象的原型链中。返回一个布尔值。
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);

console.log(auto instanceof Car); // true
console.log(auto instanceof Object); // true

// 另外,我们可以通过构建函数来判断类型
[].constructor === Array // true
(new Date()).constructor === Date // true
  • Object.prototype.toString 返回一个表示该对象的字符串,形如 '[object XXX]'
Object.prototype.toString.call([]); // '[object Array]'
Object.prototype.toString.call(false); // '[object Boolean]'
Object.prototype.toString.call(new Date()); // '[object Date]'
三、undefined 和 undeclared
  • undefined 变量在 未持有值 的时候为 undefined
  • undeclared 变量在 未声明 的时候为 undeclared
 var a;
const c = {};
// console.log(a); // undefined
// console.log(c.d); // undefined
//  console.log(b); // Uncaught ReferenceError: b is not defined
四、阻止报错

1、typeof 的安全防范机制

if (typeof DEBUG !== 'undefined') {
    console.log('DEBUG is starting')
}

2、检查所有全局变量是否是全局对象的属性

if (window.DEBUG) {
    console.log('DEBUG is starting')
}

3、依赖注入,将依赖通过参数显式地传递到函数中

function doSomethingCool(FeatureData){
    var helper = FeatureData || {}
}