Can I set the type of a Javascript object?

后端 未结 5 1453
忘了有多久
忘了有多久 2021-02-02 00:15

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

5条回答
  •  梦毁少年i
    2021-02-02 00:46

    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.

    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
    

    A more in-depth article:

    • JavaScript parasitic inheritance, power constructors and instanceof.

提交回复
热议问题