学会总结,积累
分类: JavaScript
2014-02-19 14:57:14
说明: instanceof 操作符返回一个布尔值,检测 object 是否是 constructor 的一个实例(直面翻译是检测 object 的原型链中是否存在 constructor的原型--不知道我这样说对不对)
举例:
function A(){
this.a=[];
}
function B(){
this.b = {}
}
B.prototype = new A();
var b = new B();
console.log(b instanceof B);//true
console.log(b instanceof A);//true
The typeof operator returns a string indicating the type of the unevaluated operand.
语法:typeof operand
说明: typeof 运算符返回一个字符串,这个字符串说明 operand的类型,如果operand是未定义的,则返回'undefined'(也是字符串)
举例:
typeof undefined // 'undefined';
typeof blabla //'undefined';an undefined variable
typeof function(){} // 'function';
typeof Math.sin // 'function';
typeof {a:1} // 'object';
typeof [1, 2, 4] // 'object'
The Array.isArray() method returns true if an object is an array, false if it is not.
在中,Object.prototype.toString方法的规范如下:
15.2.4.2 Object.prototype.toString()在toString方法被调用时,会执行下面的操作步骤:
1. 获取this对象的[[Class]]属性的值.
2. 计算出三个字符串"[object ", 第一步的操作结果Result(1), 以及 "]"连接后的新字符串.
3. 返回第二步的操作结果Result(2).
[[Class]]是一个内部属性,所有的对象(原生对象和宿主对象)都拥有该属性.在规范中,[[Class]]是这么定义的: 一个字符串值,表明了该对象的类型. 也就是说,把Object.prototype.toString方法返回的字符串,去掉前面固定的"[object "和后面固定的"]",就是内部属性[[class]]的值,也就达到了判断对象类型的目的.jQuery中的工具方法$.type(),就是干这个的.
在ES3中,规范文档并没有总结出[[class]]内部属性一共有几种,不过我们可以自己统计一下,原生对象的[[class]]内部属性的值一共有10种.分别是:"Array", "Boolean", "Date", "Error", "Function", "Math", "Number", "Object", "RegExp", "String".
object.constructor 返回对象的构造函数
function employee(name,job,born)
{
this.name=name;
this.job=job;
this.born=born;
}
var bill=new employee("Bill Gates","Engineer",1985);
document.write(bill.constructor === Function); //false
document.write('
');
document.write(typeof bill); //object
document.write('
');
document.write(bill.constructor); //function employee(name,job,born)
{
this.name=name;
this.job=job;
this.born=born;
}