容易搞混的JavaScript方法:typeof和instanceof
2011 年 09 月 28 日 by Ryan | Views: 94 Today Views: 1
我经常被JavaScript中的typeof和instanceof搞混的,所以认真地看了一遍。希望以后不要再忘记了。
Typeof()
1
2
3
4
5
6
7
8
//typeof() 返回6种数据类型 : number、string、boolean、object
//function和undefined。
var
a =
"string"
;
typeof
(a)
// outpout "String"
var
fn =
function
() {};
//output "function"
typeof
(fn)
//output "function"
Instanceof()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//instanceof()返回一个Boolean值。用来检测6种基本类型之一的object
//是不是某一对象(构造方法)产生的实例。用于追溯原型链。
//网上找了一个例子
var
a =
function
() {};
var
b =
function
() {};
b.prototype =
new
a;
var
c =
new
b;
var
d =
new
a;
alert(c
instanceof
a);
//true
alert(d
instanceof
a);
//true
alert(a
instanceof
Function);
//true
alert({}
instanceof
Function);
//false
a.prototype = {};
//改变原型链
alert(c
instanceof
a);
//false
alert(d
instanceof
a);
//false
Categories: | Tags: , , |
原文地址: