prototype: Simplify Class.create by establishing a prototype chain when subclassing. Closes #9342.

This commit is contained in:
Sam Stephenson 2007-08-23 21:12:02 +00:00
parent 5d3fd6f3b7
commit 6ed9095df9
3 changed files with 32 additions and 26 deletions

View File

@ -1,5 +1,7 @@
*SVN*
* Simplify Class.create by establishing a prototype chain when subclassing. Closes #9342. [Ben Newman]
* Fix Ajax.PeriodicalUpdater for compatibility with Ajax.Response. Closes #9321. [kampers]
* Ensure that classes always have an initialize method. [Mislav Marohnić]

View File

@ -1,34 +1,31 @@
/* Based on Alex Arnell's inheritance implementation. */
var Class = {
create: (function() {
var extending = { };
create: function(parent, properties) {
if (arguments.length == 1 && !Object.isFunction(parent))
properties = parent, parent = null;
return function(parent, properties) {
if (arguments.length == 1 && !Object.isFunction(parent))
properties = parent, parent = null;
function klass() {
this.initialize.apply(this, arguments);
}
klass.superclass = parent;
klass.subclasses = [];
if (parent) {
var subclass = function() { };
subclass.prototype = parent.prototype;
klass.prototype = new subclass;
parent.subclasses.push(klass);
}
if (properties) Class.extend(klass, properties);
if (!klass.prototype.initialize)
klass.prototype.initialize = Prototype.emptyFunction;
function klass() {
if (arguments[0] !== extending)
this.initialize.apply(this, arguments);
}
klass.superclass = parent;
klass.subclasses = [];
if (parent) {
klass.prototype = new parent(extending);
parent.subclasses.push(klass);
}
klass.prototype.constructor = klass;
if (properties) Class.extend(klass, properties);
if (!klass.prototype.initialize)
klass.prototype.initialize = Prototype.emptyFunction;
klass.prototype.constructor = klass;
return klass;
};
})(),
return klass;
},
extend: function(destination, source) {
var ancestor = destination.superclass && destination.superclass.prototype;

View File

@ -464,11 +464,18 @@
Class.extend(Mouse, {
sleep: function($super) {
return $super() + " ... no, can't sleep! Gotta steal cheese!";
},
escape: function(cat) {
return this.say('(from a mousehole) Take that, ' + cat.name + '!');
}
});
assertEqual('Tom: ZZZ', tom.sleep(), "added instance method not available to subclass");
assertEqual("Jerry: ZZZ ... no, can't sleep! Gotta steal cheese!", jerry.sleep());
assertEqual("Jerry: (from a mousehole) Take that, Tom!", jerry.escape(tom));
// insure that a method has not propagated *up* the prototype chain:
assertUndefined(tom.escape);
assertUndefined(new Animal().escape);
Class.extend(Animal, {
sleep: function() {