Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

.. And doesn't work in any browsers or JS engines that don't yet have Object.create, meaning it'll never work in IE < 9.

Instead, use a function like this:

    var inherits = function(child, parent) {
      var ctor = function(){};
      ctor.prototype = parent.prototype;
      child.prototype = new ctor;
      ctor.prototype.constructor = child;
    };


I'm not fully following this. Explanation anywhere? Is this how you would do inheritance?


You don't want to have to actually instantiate an object using the parent constructor in order to get an object with the parent's prototype chain attached for inheritance purposes, as you'd either have to code all constructors which will be inherited from defensively, or pass in dummy arguments to satisfy the constructor when inheriting, which could preclude using a function with no knowledge of the parent constructor such as this one.

After calling this function, the child constructor's prototype is an object with no own properties, which itself has the parent's prototype, so references to properties of the parent's prototype will resolve and objects created using the child constructor will return true for "instanceof parent".

The other step usually involved, which isn't shown here, is to put `Parent.call(this)` (with any necessary arguments) in the child constructor.


So I found Ashkenas full version of class inheritance in coffescript which simulates what I currently do with multiple crockford creates.

In my test case crockford's create is seemingly faster for this, but I'm sure I'm missing something. Someone mind educating me here?

http://jsperf.com/js-inheritance-test




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: