Created
November 13, 2015 15:16
-
-
Save JensThanx/7b0d51ed24863a64eeb0 to your computer and use it in GitHub Desktop.
private fields, getter/setter in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function MyClass( paramA ){ | |
propertyR = "this property is read-only"; | |
this.getPropertyR = function(){ | |
return propertyR; | |
}; | |
function privateMethod() { | |
return "privateMethod() is a private method"; | |
} | |
propertyRW = paramA; | |
this.getPropertyRW = function() { | |
return propertyRW; | |
}; | |
this.setPropertyRW = function( param ){ | |
propertyRW = param; | |
}; | |
this.doSomeAction = function() { | |
alert ( privateMethod() + " / " + this.getPropertyR() ); | |
}; | |
} | |
alert( "var obj = new MyClass( 'A' );"); | |
var obj = new MyClass( "A" ); | |
alert( "alert ( obj.getPropertyR() );" ); | |
alert ( obj.getPropertyR() ); | |
alert( "obj.propertyR = 'write it!';" ); | |
obj.propertyR = "write it!"; | |
alert( "alert( obj.getPropertyRW() );" ); | |
alert( obj.getPropertyRW() ); | |
alert( "obj.setPropertyRW('oh yes, write me!');" ); | |
obj.setPropertyRW("oh yes, write me!"); | |
alert( "obj.getPropertyRW();" ); | |
alert( obj.getPropertyRW() ); | |
alert( "obj.doSomeAction();" ); | |
obj.doSomeAction(); | |
alert( "obj.privateMethod();" ); | |
obj.privateMethod(); | |
alert( "That's it, check the error console. There should be two errors for trying to access objectR and privateMethod" ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment