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的更多相关文章

  1. Learning JavaScript Design Patterns The Module Pattern

    The Module Pattern Modules Modules are an integral piece of any robust application's architecture an ...

  2. Learning JavaScript Design Patterns The Observer Pattern

    The Observer Pattern The Observer is a design pattern where an object (known as a subject) maintains ...

  3. Learning JavaScript Design Patterns The Singleton Pattern

    The Singleton Pattern The Singleton pattern is thus known because it restricts instantiation of a cl ...

  4. AMD - Learning JavaScript Design Patterns [Book] - O'Reilly

    AMD - Learning JavaScript Design Patterns [Book] - O'Reilly The overall goal for the Asynchronous Mo ...

  5. 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 ...

  6. Learning PHP Design Patterns

    Learning PHP Design Patterns CHAPTER 1 Algorithms handle speed of operations, and design patterns ha ...

  7. [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. 软件模 ...

  8. [Design Patterns] 4. Creation Pattern

    设计模式是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结,使用设计模式的目的是提高代码的可重用性,让代码更容易被他人理解,并保证代码可靠性.它是代码编制真正实现工程化. 四个关键元素 ...

  9. JavaScript Design Patterns: Mediator

    The Mediator Design Pattern The Mediator is a behavioral design pattern in which objects, instead of ...

随机推荐

  1. tableView -- tips

    1. 如果发现TableView的第一个sectionHeader不显示, 那么可以断定, 你没有用代理方法来设置 sectionHeader的高度! #pragma mark - delegate ...

  2. bat写的自动部署脚本

    windows7的机器上重启服务需要关闭UAC ::编译部署项目 echo off echo 1. GatewayAdaptor echo 2. LogicService echo 3. Messag ...

  3. 【产品体验】eyepetizer开眼

    第一次写博客,内心还有点小激动呢~~本人产品新人,学习中,希望大家多多指教!  先来两张开眼的界面图坐镇——         开眼简介: appetizer for eyes 即 eyepetizer ...

  4. 独立两套DJANGO+CELERY配置(生产+测试)时要注意的一些细节

    1,生产的NGINX环境,要指定自己的目录,而不是PROJ默认的. upstream ism_host { server ; } server { listen ; server_name local ...

  5. Hibernate 一对多自身双向关联关系 用于类别表的实现

    分类:一对多自身双向关联关系 Java持久化类: package com.hyy.hibernate.one_to_many.domain; import java.util.HashSet; imp ...

  6. 李洪强iOS开发之-PCH文件的配置

    pch 可以用来存储共享信息,比如设备屏幕的宽度,高度.版本号等等 公用信息 Xcode 老版本会自动为我们创建pch文件,新版本开始不自动创建了,如果需要使用可以自己手动创建 创建完成后可以在里面定 ...

  7. asp.net 简单实现禁用或启用页面中的某一类型的控件

    我们在提交一个表单的时候,可能由于网络或服务器的原因,处理很慢,而用户在处理结果出来之前反复点击按钮提交.这样很容易造成不必要的麻烦甚至是错误.说了这么多,其实就是要实现一个禁用某些控件的一种功能.好 ...

  8. easyui源码翻译1.32--Form(表单)

    前言 使用$.fn.form.defaults重写默认值对象下载该插件翻译源码 form提供了各种方法来操作执行表单字段,比如:ajax提交, load, clear等等.当提交表单的时候可以调用va ...

  9. Java之关键字static和final的使用

    static 在Java中声明属性.方法时,可使用关键字static来修饰. 1.static变量       按照是否静态的对类成员变量进行分类可分两种:一种是被static修饰的变量,叫静态变量或 ...

  10. Android开发UI之Fragment-Tabbed Activity的使用

    使用ADT新建的时候,可以选择Tabbed Activity,选择新建一个工程. 新建的工程中,选择不同的Tab页显示不同的内容,主要是通过SectionsPagerAdapter类中的Fragmen ...