我正在尝试使用 Javascript 的一些更高级的 OO 功能,遵循 Doug Crawford 的“ super 构造函数”模式。但是,我不知道如何使用 Javascript 的 native 类型系统设置和获取对象的类型。这是我现在的方式:
function createBicycle(tires) {
var that = {};
that.tires = tires;
that.toString = function () {
return 'Bicycle with ' + tires + ' tires.';
}
}
如何设置或检索新对象的类型?如果有正确的方法,我不想创建 type
属性。
有没有办法为我的自定义对象覆盖 typeof
或 instanceof
运算符?
最佳答案
instanceof
运算符,在内部,在收集两个操作数值之后,使用抽象 [[HasInstance]](V)
操作,依赖于原型(prototype)链。
您发布的模式仅包含扩充对象,根本未使用原型(prototype)链。
如果你真的想使用instanceof
操作符,你可以结合另一个Crockford的技术,Prototypal Inheritance使用 super 构造函数,基本上是继承自Bicycle.prototype
,即使它是一个空对象,也只是为了骗过instanceof
:
// helper function
var createObject = function (o) {
function F() {}
F.prototype = o;
return new F();
};
function Bicycle(tires) {
var that = createObject(Bicycle.prototype); // inherit from Bicycle.prototype
that.tires = tires; // in this case an empty object
that.toString = function () {
return 'Bicycle with ' + that.tires + ' tires.';
};
return that;
}
var bicycle1 = Bicycle(2);
bicycle1 instanceof Bicycle; // true
更深入的文章:
关于javascript - 我可以设置 Javascript 对象的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1919295/