我可以设置Javascript对象的类型吗? [英] Can I set the type of a Javascript object?
问题描述
我正在尝试使用Javascript的一些更高级的OO功能,遵循Doug Crawford的超级构造函数模式。但是,我不知道如何使用Javascript的本机类型系统从我的对象中设置和获取类型。以下是我现在的方法:
I'm trying to use some of the more advanced OO features of Javascript, following Doug Crawford's "super constructor" pattern. However, I don't know how to set and get types from my objects using Javascript's native type system. Here's how I have it now:
function createBicycle(tires) {
var that = {};
that.tires = tires;
that.toString = function () {
return 'Bicycle with ' + tires + ' tires.';
}
}
如何设置或检索新对象的类型?如果有正确的方法,我不想创建类型
属性。
How can I set or retrieve the type of my new object? I don't want to create a type
attribute if there's a right way to do it.
推荐答案
instanceof
操作符,在收集两个操作数值后,在内部使用摘要 [[HasInstance]](V)
操作,它依赖于原型链。
The instanceof
operator, internally, after both operand values are gather, uses the abstract [[HasInstance]](V)
operation, which relies on the prototype chain.
您发布的模式仅包括扩充对象,并且根本不使用原型链。
The pattern you posted, consists simply on augmenting objects, and the prototype chain is not used at all.
如果您真的想要要使用 instanceof
运算符,您可以结合另一种Crockford的技术,使用超级构造函数的原型继承,basicall y继承自 Bicycle.prototype
,即使它是一个空对象,也只是为了傻瓜 instanceof
:
If you really want to use the instanceof
operator, you can combine another Crockford's technique, Prototypal Inheritance with super constructors, basically to inherit from the Bicycle.prototype
, even if it's an empty object, only to fool 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 parasitic inheritance, power constructors and instanceof.
这篇关于我可以设置Javascript对象的类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!