Learning JavaScript Design Patterns The Constructor Pattern
In classical object-oriented programming languages, a constructor is a special method used to initialize a newly created object once memory has been allocated for it. In JavaScript, as almost everything is an object, we're most often interested in object constructors.
Object constructors are used to create specific types of objects - both preparing the object for use and accepting arguments which a constructor can use to set the values of member properties and methods when the object is first created.
Object Creation
The three common ways to create new objects in JavaScript are as follows:
// Each of the following options will create a new empty object:
var newObject = {};
// or
var newObject = Object.create( Object.prototype );
// or
var newObject = new Object();
Where the "Object" constructor in the final example creates an object wrapper for a specific value, or where no value is passed, it will create an empty object and return it.
There are then four ways in which keys and values can then be assigned to an object:
<html>
<body>
<script type="text/javascript">
// ECMAScript 3 compatible approaches // 1. Dot syntax // Set properties
newObject.someKey = "Hello World"; // Get properties
var value = newObject.someKey; console.log(value); // 2. Square bracket syntax // Set properties
newObject["someKey"] = "Hello World"; // Get properties
var value = newObject["someKey"]; console.log(value); // ECMAScript 5 only compatible approaches
// For more information see: http://kangax.github.com/es5-compat-table/ // 3. Object.defineProperty // Set properties
Object.defineProperty( newObject, "someKey", {
value: "for more control of the property's behavior",
writable: true,
enumerable: true,
configurable: true
}); // If the above feels a little difficult to read, a short-hand could
// be written as follows: var defineProp = function ( obj, key, value ){
var config = {
value: value,
writable: true,
enumerable: true,
configurable: true
};
Object.defineProperty( obj, key, config );
}; // To use, we then create a new empty "person" object
var person = Object.create( Object.prototype ); // Populate the object with properties
defineProp( person, "car", "Delorean" );
defineProp( person, "dateOfBirth", "1981" );
defineProp( person, "hasBeard", false ); console.log(person);
// Outputs: Object {car: "Delorean", dateOfBirth: "1981", hasBeard: false} // 4. Object.defineProperties // Set properties
Object.defineProperties( newObject, { "someKey": {
value: "Hello World",
writable: true
}, "anotherKey": {
value: "Foo bar",
writable: false
} }); // Getting properties for 3. and 4. can be done using any of the
// options in 1. and 2.
</script>
</body>
</html>
As we will see a little later in the book, these methods can even be used for inheritance, as follows:
// Usage: // Create a race car driver that inherits from the person object
var driver = Object.create( person ); // Set some properties for the driver
defineProp(driver, "topSpeed", "100mph"); // Get an inherited property (1981)
console.log( driver.dateOfBirth ); // Get the property we set (100mph)
console.log( driver.topSpeed );
Basic Constructors
As we saw earlier, JavaScript doesn't support the concept of classes but it does support special constructor functions that work with objects. By simply prefixing a call to a constructor function with the keyword "new", we can tell JavaScript we would like the function to behave like a constructor and instantiate a new object with the members defined by that function.
Inside a constructor, the keyword this references the new object that's being created. Revisiting object creation, a basic constructor may look as follows:
function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
this.toString = function () {
return this.model + " has done " + this.miles + " miles";
};
}
// Usage:
// We can create new instances of the car
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
// and then open our browser console to view the
// output of the toString() method being called on
// these objects
console.log( civic.toString() );
console.log( mondeo.toString() );
The above is a simple version of the constructor pattern but it does suffer from some problems. One is that it makes inheritance difficult and the other is that functions such as toString() are redefined for each of the new objects created using the Car constructor. This isn't very optimal as the function should ideally be shared between all of the instances of the Car type.
Thankfully as there are a number of both ES3 and ES5-compatible alternatives to constructing objects, it's trivial to work around this limitation.
Constructors With Prototypes
Functions, like almost all objects in JavaScript, contain a "prototype" object. When we call a JavaScript constructor to create an object, all the properties of the constructor's prototype are then made available to the new object. In this fashion, multiple Car objects can be created which access the same prototype. We can thus extend the original example as follows:
function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
}
// Note here that we are using Object.prototype.newMethod rather than
// Object.prototype so as to avoid redefining the prototype object
Car.prototype.toString = function () {
return this.model + " has done " + this.miles + " miles";
};
// Usage:
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
console.log( civic.toString() );
console.log( mondeo.toString() );
Above, a single instance of toString() will now be shared between all of the Car objects.
Learning JavaScript Design Patterns The Constructor Pattern的更多相关文章
- Learning JavaScript Design Patterns The Module Pattern
The Module Pattern Modules Modules are an integral piece of any robust application's architecture an ...
- Learning JavaScript Design Patterns The Observer Pattern
The Observer Pattern The Observer is a design pattern where an object (known as a subject) maintains ...
- Learning JavaScript Design Patterns The Singleton Pattern
The Singleton Pattern The Singleton pattern is thus known because it restricts instantiation of a cl ...
- AMD - Learning JavaScript Design Patterns [Book] - O'Reilly
AMD - Learning JavaScript Design Patterns [Book] - O'Reilly The overall goal for the Asynchronous Mo ...
- use getters and setters Learning PHP Design Patterns
w Learning PHP Design Patterns Much of what passes as OOP misuses getters and setters, and making ac ...
- Learning PHP Design Patterns
Learning PHP Design Patterns CHAPTER 1 Algorithms handle speed of operations, and design patterns ha ...
- [Design Patterns] 3. Software Pattern Overview
When you're on the way which is unknown and dangerous, just follow your mind and steer the boat. 软件模 ...
- [Design Patterns] 4. Creation Pattern
设计模式是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结,使用设计模式的目的是提高代码的可重用性,让代码更容易被他人理解,并保证代码可靠性.它是代码编制真正实现工程化. 四个关键元素 ...
- JavaScript Design Patterns: Mediator
The Mediator Design Pattern The Mediator is a behavioral design pattern in which objects, instead of ...
随机推荐
- Automotive Security的一些资料和心得(7):AUTOSAR和Security
1. 密码模块[1] 密码模块在Services Layer Configurable and common access to 密码子程序 硬件支持密码模块 2. 应用 应用和密码子程序分离 Cry ...
- Jquer学习
1:什么是Jquery 2:jquery的例子 3:后记
- delphi xe5 android 开发数据访问手机端 解决乱码的办法
经过测试,将sqlserver里的字段由varchar 或者char 改为 nvarchar 或者nchar 然后在手机端的clientdataset 增加字段的时候数据类型选择widestrin ...
- sjtu1313 太湖旅行
Description 西山风景区是苏州著名的国家级风景区,一到暑假,游客们都蜂拥而至.作为太湖风景区的精华,西山景区吸引人的地方主要在它的群岛风光.花果丛林和名胜古迹. ginrat对这个地方向往已 ...
- asp.net DropDownList无刷新ajax二级联动实现详细过程
只适合新手制作DropDownList无刷新ajax二级联动效果: 数据库实现,添加两表如图:表1,pingpai,表2,type,具体数据库实现看自己的理解: //页面主要代码: <asp:S ...
- 很受欢迎的Linux笔记(短小精悍)
http://blog.csdn.net/xsl1990/article/details/8274028 如何知道所使用的LINUX是哪个发行版? lsb_release -a 查找某个文件的另类方法 ...
- 【HDOJ】1026 Ignatius and the Princess I
这道题搞了很久啊.搜索非常好的一道题.昨天想了2小时,以为是深搜,但后来发现深搜怎么也没法输出正确路径.今天拿宽搜试了一下,问题就是普通的队列宽搜没法得到当前时间最小值.看了一下讨论区,发现优先级队列 ...
- Webform——购物车
购物车主要实现的功能: ①在主页面可以将所有商品显示出来,包括价格,库存. ②点击购买可以累加产品,如果是同一种产品,只会累加每种产品的数量. ③查看购物车,可以查看明细,包括所购物品的名称,价格,数 ...
- WIKIOI 3243 区间翻转
3243 区间翻转 题目描述 Description 给出N个数,要求做M次区间翻转(如1 2 3 4变成4 3 2 1),求出最后的序列 输入描述 Input Description 第一行一个数N ...
- c语言_文件操作_FILE结构体解释_涉及对操作系统文件FCB操作的解释_
1. 文件和流的关系 C将每个文件简单地作为顺序字节流(如下图).每个文件用文件结束符结束,或者在特定字节数的地方结束,这个特定的字节数可以存储在系统维护的管理数据结构中.当打开文件时,就建立了和文件 ...