Object Oriented Programming in JavaScript

There are several ways to do this, such as using prototype and JavaScript object. However, simplest may be the best. Following method matches the orthodox structure of OO, which is put everything inside of a class file:

; var ObjectClass = function(inputPara)
{
; var privateAttribute_1 = inputPara
; this.publicAttribute_Temp = 200
; function privateMethod_SetInternally()
{ ; privateAttribute_1 = 100
}
; this.publicMethod_1 = function()
{ ; privateMethod_SetInternally()
; return 50*privateAttribute_1
}
; this.publicMethod_Get = function()
{ ; return privateAttribute_1
}
; this.publicMethod_SetExternally = function(valueSetLater)
{ ; privateAttribute_1 = this.publicMethod_1*valueSetLater*123456789
}
}

Please note, for private method, do not use Varibalized Function, which is also called Function Literal, Function Reference or Function Pointer, like this:

; var privateMethod_SetInternally = function () {…}

Indeed, private method privateMethod_SetInternally is useless here, because you can always set internally directly:

; privateAttribute_1 = newValue

The purpose of privateMethod_SetInternally here is to show how to call this method, as stated in publistMethod_1. There is no way for outsider to use this private method, but through publistMethod_1.

All attributes/method started with this. is the public accessible by outsider caller, or the object based on this Class.

To use this Class, an object needs to be created:

; var obj = New ObjectClass(300)
; var att1_inThere = obj.publicMethod_Get()
; obj.publicMethod_SetExternally(400)

Please note, internally, calling all public accessible attributes/methods would not need with (), while private methods need to include (). However, for outsider object, public methods need to include () as well, like above.

There is a problem. Since internally calling public methods could not be with (), there is no way to pass the parameter while calling. In here, publicMethod_SetExternally can be called and assigned with parameters externally with no problem, but can only be called without assigning parameter internally. In this case, parameter is essential, so it would generate “not defined” error.

To overcome this, publicMethod_SetExternally needs to be rewritten as follows:

; this.publicMethod_SetExternally = function()
{ ; privateAttribute_1 = this.publicMethod_1*this.publicAttribute_Temp*123456789
}

Internally, it can now be called directly:

; this.publicMethod_SetExternally

Externally, it would be called like this:

; obj.publicAttribute_Temp = 400
; obj.publicMethod_SetExternally()

No comments:

Post a Comment

Labels