您的位置:首页 > Web前端 > JavaScript

【笔记】 《js权威指南》- 第9章 类和模块 - 9.5 类和类型

2016-04-03 19:10 441 查看
如何识别一个类:

1.instanceof运算符:

判断对象是否是某个类的实例

var a = new AnyClass();
//true
a instanceof AnyClass;
AnClass.prototype.isPrototypeOf(a);


2.constructor属性:

类的构造函数

//true
a.constructor === AnyClass


3.构造函数的名称:

缺点:不支持没有constructor属性的对象, 不是所有构造函数有名字

function type(o) {
//type, class, name
var t, c, n;

if (o === null) return "null";
//NaN和自身不相等
if (o !== o) return "nan";
//可识别出原始值得类型和函数
if ((t = typeof o) !== "object") return t;
if ((c = classof(o)) !== "Object") retrn c;
if (o.constructor && typeof o.constructor === "function" && (n = o.constructor.getName())) return n;

return "Object";
}

function classof(o) {
return Object.prototype.tpString.call(o).slice(8, -1);
};

Function.prototype.getName = function () {
if ("name" in this) return this.name;
return this.name = this.toString().match(/function\s*([^(]*)\(/)[1];
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息