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

Eva*_*ske 14 javascript oop types typeof instanceof

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

function createBicycle(tires) {
    var that = {};
    that.tires = tires;
    that.toString = function () {
        return 'Bicycle with ' + tires + ' tires.';
    }
}
Run Code Online (Sandbox Code Playgroud)

如何设置或检索新对象的类型?type如果有正确的方法,我不想创建属性.

有没有办法覆盖typeofinstanceof运营商对我的自定义对象?

CMS*_*CMS 15

instanceof操作者,在内部,后两个操作数的值是收集,使用抽象[[HasInstance]](V)操作,这依赖于原型链.

您发布的模式仅包括扩充对象,并且根本不使用原型链.

如果你真的想使用instanceof运算符,你可以将另一个Crockford的技术,Prototypal Inheritance超级构造函数结合起来,基本上是从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
Run Code Online (Sandbox Code Playgroud)

更深入的文章:

  • ES6 允许您覆盖 [`[Symbol.hasInstance]` 函数](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance),该函数覆盖 `instanceof ` 有效。但请注意,在任何地方仅使用一次可能会导致页面中*所有* JavaScript 的全局显着减慢 - 请参阅[Google V8 演示文稿的幻灯片 29 至 34](https://docs.google.com/presentation/d/ 1wiiZeRQp8-sXDB9xXBUAGbaQaWJC84M5RNxRyQuTmhk/edit#slide=id.g1b86cc14ce_0_12) 表示“在任何地方安装 Symbol.hasInstance 属性都会禁用虚拟机的全局快速路径”。 (2认同)