/* Class Person. */
function Person(name) {
this.name = name;
}
Person.prototype.getName = () {
return this.name;
}
var reader = new Person('John Smith');
reader.getName();
Author(name,books) {
Person.call(this,name); // Call the superclass' constructor in the scope of this.
this.books = books; Add an attribute to Author.
}
Author.prototype = new Person(); Set up the prototype chain.
Author.prototype.constructor = Author; Set the constructor attribute to Author.
Author.prototype.getBooks = function() { Add a method to Author.
.books;
};
var author = [];
author[0] = new Author('Dustin Diaz',['JavaScript Design Patterns']);
author[1] = new Author('Ross Harmes',1)">]);
console.log(author[1].getName());
console.log(author[1].getBooks());
extend(subClass,superClass) {
var F = () {};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
}
Class Author. ,name);
this.books = books;
}
extend(Author,Person);
Author.prototype.getBooks = .books;
};
Extend function,improved. subClass;
subClass.superclass = superClass.prototype;
if(superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
}
.books;
};
Author.prototype.getName = var name = Author.superclass.getName.call();
return name + ',Author of ' + this.getBooks().join(',');
};
var Person = {
name: 'default name'() {
.name;
}
};
var reader = clone(Person);
alert(reader.getName()); This will output 'default name'.
reader.name = 'John Smith';
alert(reader.getName()); This will now output 'John Smith'.
var Author = clone(Person);
Author.books = []; Default value.
Author.getBooks = .books;
}
[];
author[0] = clone(Author);
author[0].name = 'Dustin Diaz';
author[0].books = ['JavaScript Design Patterns'];
author[1] = clone(Author);
author[1].name = 'Ross Harmes';
author[1].books = ['JavaScript Design Patterns'];
author[1].getName();
author[1].getBooks();
clone(object) {
F() {}
F.prototype = object;
F;
}
var Mixin = () {};
Mixin.prototype = {
serialize: var output = [];
for(key in ) {
output.push(key + ': ' + [key]);
}
return output.join(',1)">);
}
};
augment(Author,Mixin);
var author = ]);
var serializedString = author.serialize();
augment(receivingClass,givingClass) {
for(methodName in givingClass.prototype) {
if(!receivingClass.prototype[methodName]) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
if(arguments[2]) { Only give certain methods.
for(var i = 2,len = arguments.length; i < len; i++) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
}
else { Give all methods.
givingClass.prototype) {
receivingClass.prototype[methodName]) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
}