dokumen.tips_introduction-to-object-oriented-javascript
dokumen.tips_introduction-to-object-oriented-javascript
Overview
ninemsn.portal.ads = ninemsn.portal.ads || {}
...
...
//and even further down some code which clears the ninemsn namespace
//do this
(function() {
var today = new Date();
var friendlyDate = today.getDate() + '/'
+ today.getMonth() + '/' + today.getgetFullYear();
$('#year').html(friendlyDate);
}());
Namespaces
Treat it like a public toilet. You can't avoid it, but while
you're there have the least contact possible: you have no
idea who has been here, or what they've done, and no idea
who and what will come after.
- Dmitry Baranovskiy
Classes
To create a class we build a class constructor function. When this function is
called it returns a new instance of the class.
How this constructor function constructs the instance can vary. There are
two main methods:
• Creating instances dynamically
• Creating instances using the Prototype
Prototype
Method 1
Method 2
Method 3
s
o
r
P
s
o
r
P
3500
3000
2500
2000
1500
1000
500
0
1 10 100 1000 10000 100000 1000000
Prototype 0 0 0 1 7 60 650
Dynamic 0 0 1 2 34 258 3592
Classes
Memory Consumption (MB)
600
500
400
300
200
100
0
1 10 100 1000 10000 100000 1000000
Prototype 1.64 1.64 1.64 1.7 2.32 8.9 75.15
Dynamic 1.63 1.64 1.69 2.12 6.48 50.41 527.22
Classes
var Man = function () {
};
ben.speak('Hello');
ben.wave();
Classes
var Man = function (location) {
//public methods
//instance constructor
};
ben.speak('Hello');
ben.wave();
Encapsulation
Encapsulation is achieved using a feature of JavaScript called closures.
What is a closure?
• A closure is the local variables for a function - kept alive after the function
has returned
• A closure is a stack-frame which is not de-allocated when the function
returns (as if a 'stack-frame' were malloc'ed instead of being on the
stack!).
Encapsulation
An example of a closure:
function sayHello(name) {
//private constants
//private attributes
var _root;
//public methods
...
//instance constructor
_root = $(location);
};
Encapsulation
Inheritance
Inheritance is implemented by a child class calling the constructor of it’s
parent. The scope of the child is passed to the parent.
var Parent = function() {
this.methodA = function() { ... };
this.methodB = function() { ... };
};
};
Parent.call( this);
this.methodA = function() {
_base.methodA();
};
};
Inheritance
Interfaces
Interfaces are implemented using a concept called Duck Typing.
Duck Typing:
When I see a bird that walks like a duck and swims like a duck and quacks like a
duck, I call that bird a duck.
- James Whitcomb Riley
Interface.ensureImplements(ben , IPerson);
Interfaces
Singleton Pattern
Is useful when you only want to guarantee only one instance of your class
exists, e.g. API or Configuration objects.
function constructor() {
this.getPerson = function (location) { ... }
};
var _instance;
function constructor() {
};
return {
getInstance : function () {
};
} ();
function privateStaticMethod() {
//something useful
};
function constructor() {
this.publicMethod = function () {
privateStaticMethod();
...
};
};
return constructor;
} ();
Static Attributes/Methods
var Class = function () {
function constructor() {
this.publicMethod = function () {
constructor.publicStaticMethod();
...
};
};
return constructor;
} ();
Class.publicStaticMethod();
Static Attributes/Methods
var Class = function () {
var _instanceCount = 0;
function constructor() {
_instanceCount ++;
};
constructor.getInstanceCount = function() {
return _instanceCount;
};
return constructor;
} ();
Static Attributes/Methods
var instances = [];
Class.getInstanceCount(); //returns 10
Static Attributes/Methods
Solution Encapsulation
Encapsulation at a class level is a great way of hiding the inner workings of a
class, but sometimes we want to hide the inner workings of a solution.
Usually only a small number of classes need to be accessible, the rest can
remain hidden in a closure.
demos.demo6.MoodType = MoodType;
demos.demo6.PersonFactory = PersonFactory;
} (demos));
Solution Encapsulation
JavaScript Build
Keeping each class in its own file makes big solutions easy to maintain, but
we don’t want to include each file individually on the page.
We can use MS Build to combine all files in a solution into a single file for use
on the page.
We can also use MS Build to minify this single combined file to reduce the
file size.
JavaScript Build
MS Build is an XML file containing instructions telling the builder what to do.
The JavaScript build is broken down into the following steps:
Declare variables (such as the path to the minified file, solution version etc)
<PropertyGroup >
<Project>demo7</Project>
<Version>1.0.0</Version>
<MergedFile>$(SourceLocation)js\demo7\$(Project)-latest.js </MergedFile>
<CompressedFile >$(SourceLocation)js\demo7\$(Project)-
latest.min.js </CompressedFile >
</PropertyGroup >
JavaScript Build
Clear any read-only flags on the output files:
<ItemGroup>
</ItemGroup>
JavaScript Build
Merge the individual files into a combined file:
<MergeFiles
InputFiles="@(Files)"
OutputFile="$(MergedFile) "
Project="$(Project)"
Version="$(Version)"
<CompressorTask
JavaScriptFiles ="$(MergedFile) "
ObfuscateJavaScript ="True"
PreserveAllSemicolons ="True"
DisableOptimizations ="False"
EncodingType ="Default"
DeleteJavaScriptFiles ="False"
LineBreakPosition ="-1"
JavaScriptOutputFile ="$(CompressedFile) "
LoggingType ="ALittleBit"
ThreadCulture ="en-au"
IsEvalIgnored ="False" />
JavaScript Build
Add version to the file name:
<Copy
SourceFiles=
"$(MergedFile);$(CompressedFile) "
DestinationFiles =
We can build the solution as individual files and merge them together.
Consider this single file to be our solution.
We can then create a file which is the wrapper. This wrapper encapsulates
the solution, so we need to take the solution file and place it into this
wrapper.
This can be fixed by the wrapper. It can declare two namespaces, a public
one visible to everyone, and a private one visible to only classes within the
solution.
All classes attach themselves to the private namespace. The wrapper then
selectively exposes the classes which should be public.
JavaScript Build
(function () {
demos.demo7 = {};
{library}
demosExternal.demo7.MoodType = demos.demo7.MoodType;
demosExternal.demo7.PersonFactory = demos.demo7.PersonFactory;
} ());
JavaScript Build
Summary