简体   繁体   中英

Javascript extend class with props?

I have class defined as:

function MyClass() {

}

MyClass.prototype = {
       init: function() {
                 alert('My parent class!');
       },
       method1: function() {},
       method2: function() {}
};

and properties object:

{
     init: function() {
               MySubClass.superclass.init.apply(this, arguments);
               alert('test!');
     },

     test: function() {
               alert();
     }
}

and i need function which will be extends base class (MyClass) with props (object) and return NEW extended subclass (to MySubClass):

MySubclass = extend(MyClass, {
     init: function() {
               MySubClass.superclass.init.apply(this, arguments);
               alert('test!');
     },

     test: function() {
               alert();
     }
});

Constructor must be replaced by new constructor (from init).

I need a correct way.

Why it's not working good?

extend: function(bc, o) {
        // result class (apply only first constructor)
        var cls = function() {};
        cls.prototype = bc.prototype;

        for (var k in o)
            cls.prototype[k] = o[k];

        cls.superclass = bc.prototype;

        return cls;
    }

Your extend function would have to look something like this - now this is much simpler than how you should really implement it but it should work:

var extend = function(Super, props) {
   var sinstance = new Super()
   var sclass = props.constructor || sinstance.constructor;
   sclass.prototype.super = sinstance;
   sclass.prototype.constructor = Super;

   //use underscore extend prototypes cause im too lazy to type it out
   _.extend(sclass.prototype, sinstance, props);
   return sclass;
}

Calling subclass.super.call(this, props...) allows you access overridden super methods.

Just tested and this works if underscore js is on the page:

function MyClass() {

}
MyClass.prototype = {
       init: function() {
                 alert('My parent class!');
       },
       method1: function() {},
       method2: function() {}
};

MySubclass = extend(MyClass, {
     init: function() {
               this.super.init.apply(this, arguments);
               alert('test!');
     },

     test: function() {
               alert();
     }
});

var test = new MySubclass();
test.init("yo"); //alerts My parent class

For your update you can also do this:

MySubclass2 = extend(MyClass, {
     constructor: function() {
        this.init();
     },

     init: function() {
               this.super.init.apply(this, arguments);
               alert('test!');
     },

     test: function() {
               alert();
     }
});

var test2 = new MySubclass2();//alerts My parent class

If you are open to using a library, use _.extend from underscore.js . Otherwise, add this code to your codebase:

extend = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      if (source) {
        for (var prop in source) {
          obj[prop] = source[prop];
        }
      }
    });
    return obj;
  };

我看到你用jQuery标记 - 如果你确实使用jQuery,你可能会对使用$ .extend感兴趣

Take a look at this: https://github.com/haroldiedema/joii

var BaseClass = function() 
{
    this.some_var = "foobar";

    /**
     * @return string
     */
    this.someMethod = function() {
        return this.some_var;
    }
};

var MyClass = new Class({ extends: BaseClass }, function()
{
    /**
     * @param string value
     */
    this.__construct = function(value)
    {
        this.some_var = value;
    }

})

Usage:

var obj = new MyClass("Hello World!");
console.log( obj.someMethod() ); // Hello World!

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