JavaScriptの継承メモ

posted by cheesepie on 2009.06.16, under javascript
30th

いつも忘れちゃうのでメモ。

function extend( self, other ) {
 for( var property in other ) {
  self[property] = other[property];
 }
 return self;
}

var Klass = function() {
 return function() {
  return this;
 }
};
Klass.create = function() {
 var f = function() {
  this.initialize.apply( this, arguments );
 };
 f.prototype.initialize = function() {};
 f.isClass = true;
 f.extend = function( other ) {
  extend( f.prototype, other );
  return f;
 };
 return f;
};
Klass.extend = function( base_class ) {
 if( base_class.isClass ) {
  var child = Klass.create();
  child.prototype = new base_class;
  return child;
 } else {
  var base = Klass();
  base.prototype = base_class;
  var child = Klass.create();
  child.prototype = new base;
  return child;
 }
};

使い方。

var Foo = Klass.create();
Foo.prototype = {
 initialize: function( name ) {
  this.name = name;
 },
 getName: function() {
  alert( this.name );
 }
};
var Bar = Klass.extend( Foo ).extend( {
 setName: function( name ) {
  this.name = name;
 }
} );

var f = new Foo( "bob" );
var b = new Bar( "john" );
b.setName( "michel" );

f.getName(); // bob
b.getName(); // michel

Comments are closed.

TrackBack URL :

pagetop