我可以设置 Javascript 对象的类型吗?

2024-01-12

我正在尝试遵循 Doug Crawford 的“超级构造函数”模式,使用 Javascript 的一些更高级的 OO 功能。但是,我不知道如何使用 Javascript 的本机类型系统设置和获取对象的类型。我现在的情况是这样的:

function createBicycle(tires) {
    var that = {};
    that.tires = tires;
    that.toString = function () {
        return 'Bicycle with ' + tires + ' tires.';
    }
}

如何设置或检索新对象的类型?我不想创建一个type属性(如果有正确的方法的话)。

有没有办法覆盖typeof or instanceof我的自定义对象的运算符?


The instanceof http://bclary.com/2004/11/07/#a-11.8.6运算符在内部,在两个操作数值聚集之后,使用抽象[[HasInstance]](V) http://bclary.com/2004/11/07/#a-15.3.5.3操作,依赖于原型链。

您发布的模式仅包含增强对象,并且根本不使用原型链。

如果你真的想使用instanceof操作员,您可以结合另一个 Crockford 的技术,原型继承 http://javascript.crockford.com/prototypal.html with 超级构造者,基本上继承自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 寄生继承、强大的构造函数和instanceof。 http://higher-order.blogspot.com/2008/02/javascript-parasitic-inheritance-super.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我可以设置 Javascript 对象的类型吗? 的相关文章

随机推荐