书中有一节讲给类型添加方法,讲解的示例如下:

Function.prototype.method = function(name, func) {

  this.prototype[name] = func;

  return this;

};

Number.method('integer',function() {

  return Math[this < 0 ? 'ceiling' : 'floor'](this);

});

有没有疑问呢?method是函数类型的方法,如果有var fun  = function(){};自然fun可以调用method方法,即有:

fun.method("toString",fun(){

  ...

  return string; 

});

但是作为类型的Number为什么可以这么用呢?

其实答案很简单,类型其实是构造函数而已,如 var one = new Number(1);构造函数也是函数,因此自然可以调用。

接下来的问题来了:

var falseObject = new Boolean(false);

var falseValue = false;

 

alert(typeof falseObject); //object

alert(typeof falseValue); //boolean

alert(falseObject instanceof Boolean); //true

alert(flaseValue instanceof Boolean); //false 

alert(Object instanceof Function); //true

alert(Function instanceof Object); //true

 

JavaScript有5种简单数据类型(也称为基本数据类型):Undefined、Null、Boolean、Number和String。还有一种复杂数据类型——Object(对象)。

基本类型可以用typeof来检测,对一个值使用tupeof操作符可能返回下列某个字符串:

"undefind"——如果这个值未定义;

"boolean"——如果这个值是布尔值;

"string"——如果这个值是字符串;

"number"——如果这个值是数值;

"object"——如果这个值是对象或nill;

"function" ——如果这个值是函数。

Boolean、Number、String是三种引用类型,由其构造的实例是自然是对象,即alert(typeof falseObject); //object;

而由字面量定义的布尔值、数值、字符串是基本数据类型,所以有:alert(typeof falseValue); //boolean。

 

对于引用类型的检测使用instanceof操作符。简单来说,如果变量是给定引用类型(由构造函数表示)的实例,那么instanceof操作符就会返回true,所以:

alert(falseObject instanceof Boolean); //true

JavaScript所有引用类型的值都是Object的实例。因此,在检测一个引用类型值和Object构造函数时,instanceof操作符始终会返回true,所以:

alert(Function instanceof Object); //true

如果使用instanceof操作符检测基本类型的值,则该操作符始终会返回false,因为基本类型不是对象,所以:

alert(flaseValue instanceof Boolean); //false

另一方面Object, Function, Array等等这些都被称作是构造“函数”,他们都是函数。而所有的函数都是构造函数Function的实例,所以:

alert(Object instanceof Function); //true

 

有关instanceof 操作符的更深入讨论涉及到JavaScript的核心——原型链(prototype chain)的知识,我们放到以后再讨论。