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 ...
随机推荐
- Vm image download resource
http://vmdepot.msopentech.com/List/Index http://www.hanselman.com/blog/Over400VirtualMachineImagesOf ...
- SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-010-Introduction为类增加新方法@DeclareParents、<aop:declare-parents>
一. 1.Introduction的作用是给类动态的增加方法 When Spring discovers a bean annotated with @Aspect , it will automat ...
- JMP软件中的晶圆图( Wafer Map)分析
关键词:芯片 良率分析 晶圆图 质量管理 JMP Minitab 半导体芯片的生产,简单来讲,是将电路通过各种复杂的物理化学方法制作到晶圆上,在生产的最后阶段会进行不同电性功能的测试以确保产品的功能性 ...
- python的whl文件安装
python27win32安装:https://www.python.org/downloads/ 下载2.7的 安装中一路下一步即可: 配置python系统环境变量: 新建: PY ...
- PHP FTP上传文件
第一步:建立一个新的 FTP 连接. ftp_connect(host,port,timeout); host必需,规定要连接的 FTP 服务器,可以是域名或 IP 地址,后面不应以斜线结 ...
- C# SerialPort的简单使用
SerialPort中串口数据的读取与写入有较大的不同.由于串口不知道数据何时到达,因此有两种方法可以实现串口数据的读取.一.线程实时读串口:二.事件触发方式实现.由于线程实时读串口的效率不是十分高效 ...
- Linux kernel ‘aac_send_raw_srb’函数输入验证漏洞
漏洞名称: Linux kernel ‘aac_send_raw_srb’函数输入验证漏洞 CNNVD编号: CNNVD-201311-422 发布时间: 2013-11-29 更新时间: 2013- ...
- 【随笔】这段时间没有写博客是因为一边看Qt5的帮助文档一边写小程序
长话短说,因为和做程序员的以前的同学联系了一下,知道自己有很多不足,加之接到一个培训机构的人打来的电话稍微打击了一下,虽然那个人满嘴跑火车想装做和我很谈得来,但是我依然看到了自己没有写过任何命令行以外 ...
- linux 系统获取网络ip, mask, gateway, dns信息小程序
net_util.c #define WIRED_DEV "eth0" #define WIRELESS_DEV ...
- Go Hello World!
有些事应该坚持去做 当你半途而废的时候意味着你又要重新开始.那么 Golang Hello world! Java Android 新手 学习 Golang First Day ! go 语言下载: ...