简体   繁体   中英

Javascript Prototypal inheritance

I am reading Javascript Web Applications by Alex Maccaw. Below is a snippet where a Class constructor is built.

    var Class = function(parent){
        var klass = function(){
        this.init.apply(this, arguments);
     };

  // Change klass' prototype 
    if (parent) {
        var subclass = function() { };
        subclass.prototype = parent.prototype;
        klass.prototype = new subclass;
    };

  klass.prototype.init = function(){};

  // Shortcuts
  klass.fn = klass.prototype;
  klass.fn.parent = klass;
  klass._super = klass.__proto__;      

  /* include/extend code... */

  return klass;
};

The abit i'm interested in is

    var subclass = function() { };
    subclass.prototype = parent.prototype;
    klass.prototype = new subclass;

Why doesn't he go

    klass.prototype = parent.prototype;

He explains it: "This little dance around creating a temporary anonymous function prevents instances from being created when a class is inherited". This still doesn't make sense to me, how would

    klass.prototype = parent.prototype;

make instances be created?

Because then anything you put on klass.prototype would also go on parent.prototype since they're the same object.

What he's doing is making a new object that inherits from parent.prototype , and assigning that object to klass.prototype , so that any properties added to it, don't get put on parent.prototype .


FYI, a more modern way to do that would be to use Object.create()

klass.prototype = Object.create(parent.prototype);

This accomplishes basically the same thing.


This sentence you pointed out:

" "This little dance around creating a temporary anonymous function prevents instances from being created when a class is inherited""

...is an odd way to explain it, unless there's a greater context where it makes sense. Perhaps he means to say that you don't need to invoke the parent constructor in order to obtain an object that inherits from parent.prototype .

If you did this:

klass.prototype = new parent();

It would accomplish the same thing, except that the parent constructor would be invoked, and there could be undesired side effects in doing so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM