| Constructor Pattern | |
| A constructor is used to create specific types of objects -both preparing the object for use and accepting arguments which a constructor can use to set properties and methods when the object first created. | |
| Object Creation | |
| The three common ways to create new objects in JavaScript are as follows: | |
| var newObject = {}; | |
| var newObject = Object.create( Object.prototype ); | |
| var newObject = new Object(); | |
| There are then four ways in which keys and values can then be assigned to an object: | |
| a) Dot syntax | |
| //Set Properties | |
| newObject.someKey = "Hello World"; | |
| //Get Properties | |
| var value = newObject.someKey; | |
| b) Square bracket syntax | |
| //Set Properties | |
| newObject["someKey"] = "Hello World"; | |
| //Get Properties | |
| var value = newObject["someKey"]; | |
| c) Object.defineProperty | |
| //Set Properties | |
| Object.defineProperty( newObject, "someKey", { | |
| value: "more control", | |
| writable: true, | |
| enumerable: true, | |
| configurable: true | |
| }); | |
| OR | |
| var defineProp = function ( obj, key, value){ | |
| var config = { | |
| value: value, | |
| writable:true, | |
| enumerable: true, | |
| configurable: true, | |
| }; | |
| Object.defineProperty( obj, key, config ); | |
| So in order to use this we have to create an 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); | |
| Constructors With Prototypes | |
| When we call a constructor to create an object then we can access all the constructor's properties through prototype. | |
| 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 |
Σχόλια
Δημοσίευση σχολίου