The Prototype Pattern

The prototype pattern focuses on creating an object that can be used as a blueprint for other objects through prototypal inheritance. This pattern is inherently easy to work with in JavaScript because of the native support for prototypal inheritance in JS which means we don’t need to spend time or effort imitating this topology.

This article is part of a series called JavaScript Design Patterns.

Advantages

Disadvantages

Example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// build our blueprint object
var MyBluePrint = function MyBluePrintObject() {
this.someFunction = function someFunction() {
alert( 'some function' );
};
this.someOtherFunction = function someOtherFunction() {
alert( 'some other function' );
};
this.showMyName = function showMyName() {
alert( this.name );
};
};
 
function MyObject() {
this.name = 'testing';
}
MyObject.prototype = new MyBluePrint();
 
// example usage
var testObject = new MyObject();
testObject.someFunction(); // alerts "some function"
testObject.someOtherFunction(); // alerts "some other function"
testObject.showMyName(); // alerts "testing"

Additional Resources

http://www.uipress.com/patterns-in-javascript-the-prototype-pattern/#.Uh9GQmRgYWA
http://www.geraintwilliams.net/2013/03/javascript-design-patterns.html
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#prototypepatternjavascript

Other Common JS Patterns

The Module Pattern
The Revealing Module Pattern
The Singleton Pattern
The Observer Pattern
The Mediator Pattern
The Prototype Pattern
The Facade Pattern
The Factory Pattern

2 responses!

JavaScript应用设计模式 | chainding said: (7 months ago) Reply

[…] 原型模式 […]

JavaScript应用设计模式 | 游侠博客 said: (4 months ago) Reply

[…] 原型模式 […]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>