Prototype for private sub-methods - javascript

I have code that looks like this:
var baseClass = function() {
// CODE
var subClass = function() {
// MORE CODE
}
}
Adding methods to baseClass is fine, I just use
baseClass.prototype.newMethod = function () {
// NEW CODE
}
My question is how should I add methods to subClass? Is the only way to simply make it a public method?
######## EDIT ##############
OK so I've rearranged the code so the subClass is outside the baseClass. I pass in baseClass so subClass can still access the properties of the instance of baseClass.
var baseClass = function() {
var base = this;
this.property_a = 1;
this.property_b = 5;
var sub = new subClass(base);
// CODE
}
var subClass = function(parent) {
var sub = this;
this.property_c = 1;
this.method_a = function() {
return sub.property_c + parent.property_a;
}
// MORE CODE
}
this is fine and works, but now I have a new problem of when I add a method using prototype:
subClass.prototype.method_b = function(){
return sub.property_c + parent.property_b;
}
I get an error saying parent isn't defined.
Basically I have a fairly simple web application that has two sides, a viewing side and an editing side. I build the base class which includes everything necessary for viewing, and I want to add the methods required for editing in a different file so they're only loaded when a user is on the editing page.

Why do you declare that subclass in the base class? Doesn't make sense to me.
You can add to the subclass's prototype whereever it is in you scope. In your code it would be
var baseClass = function() {
// CODE
var subClass = function() {
// MORE CODE
}
subClass.prototype = {
...
}
}
But I'd suggest to put it out of the base class constructor. If you want it private for some reason, add a closure:
(function(){
baseClass = function() { // public
// CODE
}
baseClass.prototype = {...};
var subClass = function() { // private
// MORE CODE
}
subClass.prototype = Object.create(baseClass.prototype);
subClass.prototype.newMethod = function () { ... }
})()
EDIT to answer the extended question:
Ah, subClass doesn't inherit from baseClass! We had expected that, otherwise it may be OK to have it inside the constructor. Then, the same prototype could have been added to each of the different subClass constructors:
var subproto = {
method_b: = function(){
// manipulate "this"
},
...
};
function baseClass() {
// some code
function sub() {
// is a constructor for subs which belong to this specif base intance
...
}
sub.prototype = subproto; // the sub constructors of each base instance
// have the same prototype
var x = new sub(),
y = new sub(); // example usage of the sub constructor
}
baseClass.prototype = {...}
Else, if you want one common sub constructor (outside of function baseClass), you may give the base instance the sub belongs to as an argument to the constructor - as you did. Of course the sub (both internal and external methods) can only access public properties of that base instance.
The mistake you made in your rearranged code is that your prototype ("external") methods tried to access the private parent variable from the sub constructor. As you say, "error saying parent isn't defined".
var subClass = function(parent) {
var sub = this;
this.parent = parent; // make it public
this.property_c = 1;
this.method_a = function() {
return sub.property_c + parent.property_a;
}
// MORE CODE
}
subClass.prototype.method_b = function(){
// prototype functions can only access public properties
// i.e. privileged methods, public attributes and other prototype properties
return this.property_c + this.parent.property_b;
}

You will have to define the methods in the same context as you define subClass:
var baseClass = function() {
// CODE
var subClass = function() {
// MORE CODE
}
subClass.prototype.newMethod = function () { ... }
}
If that's not possible, then you will need to expose subClass to the appropriate context or provide a mechanism from baseClass to extend subClass.

If you really want to keep the subclass private, you could hide the definitions in a closure:
var BaseClass = (function() {
function BaseClass() { ... };
function SubClass() { ... };
BaseClass.prototype.foo = function() { ... };
SubClass.prototype.foo = function() { ... };
return BaseClass;
})();
I have personally found this kind of closure-enforced protection to be more trouble than it's worth (ex, makes debugging more difficult)… But if you wanted to do it, that's how you would.

Related

Javascript inheritance and encapsulation, done efficiently

Coming from a C++ / Objective-C background, I'm trying to learn how to correctly and efficiently reproduce the patterns of inheritance and encapsulation in Javascript. I've done plenty of reading (Crockford etc.) and while there are plenty of examples of how to achieve one or the other, I'm struggling with how to combine them without introducing significant negatives.
At the moment, I have this code:
var BaseClass = (function() {
function doThing() {
console.log("[%s] Base-class's 'doThing'", this.name);
}
function reportThing() {
console.log("[%s] Base-class's 'reportThing'", this.name);
}
return function(name) {
var self = Object.create({});
self.name = name;
self.doThing = doThing;
self.reportThing = reportThing;
return self;
}
}());
var SubClass = (function(base) {
function extraThing() {
console.log("[%s] Sub-class's 'extraThing'", this.name);
}
function doThing() {
console.log("[%s] Sub-class's replacement 'doThing'", this.name);
}
return function(name) {
// Create an instance of the base object, passing our 'name' to it.
var self = Object.create(base(name));
// We need to bind the new method to replace the old
self.doThing = doThing;
self.extraThing = extraThing;
return self;
}
}(BaseClass));
It mostly does what I want:
// Create an instance of the base class and call it's two methods
var base = BaseClass("Bert");
base.doThing(); // "[Bert] Base-class's 'doThing'"
base.reportThing(); // "[Bert] Base-class's 'reportThing'"
var other = BaseClass("Fred");
// Create an instance of the sub-class and call it's three methods (two from the base, one of it's own)
var sub = SubClass("Alfred");
sub.doThing(); // "[Alfred] Sub-class's replacement 'doThing'"
sub.extraThing(); // "[Alfred] Sub-class's 'extraThing'"
sub.reportThing(); // "[Alfred] Base-class's 'reportThing'"
But, there's (at least!) two issues:
I'm not convinced the prototype chain is intact. If I substitute a method in the prototype via one instance of a sub-class, other instances don't see it:
No encapsulation of .name property
I'm replacing the prototype's implementation of a function like this:
Object.getPrototypeOf(oneInstance).reportThing = function() { ... }
otherInstance.reportThing() // Original version is still called
That's perhaps not a significant problem, but it is causing me to doubt my understanding.
Private variables is something I want to implement efficiently though. The module pattern of variable hiding doesn't help here, as it causes function definitions to exist per-object. I'm probably missing a way of combining patterns, so is there a way of achieving private variables without duplicating functions?
This is usually how I tackle inheritance and encapsulation in JavaScript. The defclass function is used to create a new class that doesn't inherit from any other class and the extend function is used to create a new class which extends another class:
var base = new BaseClass("Bert");
base.doThing(); // "Bert BaseClass doThing"
base.reportThing(); // "Bert BaseClass reportThing"
var sub = new SubClass("Alfred");
sub.doThing(); // "Alfred SubClass replacement doThing"
sub.extraThing(); // "Alfred SubClass extraThing"
sub.reportThing(); // "Alfred BaseClass reportThing"
var other = new SubClass("Fred");
SubClass.prototype.reportThing = function () {
console.log(this.name + " SubClass replacement reportThing");
};
other.reportThing(); // Fred SubClass replacement reportThing
<script>
function defclass(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
function extend(constructor, keys) {
var prototype = Object.create(constructor.prototype);
for (var key in keys) prototype[key] = keys[key];
return defclass(prototype);
}
var BaseClass = defclass({
constructor: function (name) {
this.name = name;
},
doThing: function () {
console.log(this.name + " BaseClass doThing");
},
reportThing: function () {
console.log(this.name + " BaseClass reportThing");
}
});
var SubClass = extend(BaseClass, {
constructor: function (name) {
BaseClass.call(this, name);
},
doThing: function () {
console.log(this.name + " SubClass replacement doThing");
},
extraThing: function () {
console.log(this.name + " SubClass extraThing");
}
});
</script>
Read the following answer to understand how inheritance works in JavaScript:
What are the downsides of defining functions on prototype this way?
It explains the difference between prototypes and constructors. In addition, it also shows how prototypes and classes are isomorphic and how to create “classes” in JavaScript.
Hope that helps.
The simple recipe follows:
function BaseClass(someParams)
{
// Setup the public properties, e.g.
this.name = someParams.name;
}
BaseClass.prototype.someMethod = function(){
// Do something with the public properties
}
Now the inheritance occurs this way
function SubClass(someParams)
{
// Reuse the base class constructor
BaseClass.call(this, someParams);
// Keep initializing stuff that wasn't initialized by the base class
this.anotherProperty= someParams.anotherProperty;
}
// Copy the prototype from the BaseClass
SubClass.prototype = Object.create(BaseClass.prototype);
SubClass.prototype.constructor = SubClass;
// Start extending or overriding stuff
SubClass.prototype.someMethod = function(){
// In case you still wanna have the side effects of the original method
// This is opt-in code so it depends on your scenario.
BaseClass.prototype.someMethod.apply(this, arguments);
// Override the method here
}
Taken from:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
P.S. Object.create may not be supported on all old browsers, but don't worry, there's a polyfill for that in this link. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
If you want to preserve the prototype chain, you must override and use .prototype:
Example:
Main Class:
function BaseClass(){
}
BaseClass.prototype.doThing = function(){...}
SubClass:
function SubClass(){
}
SubClass.prototype= new BaseClass();
SubClass.prototype.extraThing = function(){};
Now, whenever you change extraThing or doThing it gets replaced everywhere.
The name property is accessible as a public variable (it's not static).
If you want it static, you must put it in prototype.
If you want it private, you mast make it function local:
function BaseClass(nameParam){
var name = nameParam;
}
To create an object simply call the function:
var testObj = new BaseClass("test");
testObj.doThing();
If you want to combine private variables with rewritable functions, you might find your answer here. But if you are able to rewrite the function that has access to the private variable, it's not really a private variable anymore.

First Attempt at Javascript Objects & Inheritance: is it correct

I am attempting to learn how to create classes in Javascript & how to perform object inheritance. I have followed some tutorials but I am not sure if my code is correct.
Am I creating public functions & attributes correctly? If not, what should I change?
Am I creating privileged functions & attributes correctly? If not, what should I change?
Am I creating private functions & attributes correctly? If not, what should I change?
Am I overriding functions correctly?
Am I performing inheritance correctly?
If theres anything wrong can you show me how the code should be?
Heres my simple code that creates a base class then a child class:
/* Base Object Class */
function BaseClass( /*string*/ objType )
{
/* Public: */
this.name = "blah";
BaseClass.prototype.getName = function()
{
return this.name;
}
BaseClass.prototype.setName = function( newName )
{
var oldName = this.name;
this.name = newName;
return oldName;
}
/* Private: */
var attributeMap = {};
this.constructor = function()
{
// this objects default constructor. Is this correct?
attributeMap["type"] = objType;
attributeMap["uniqueID"] = "Base"+(++INSTANCE_COUNT);
}
/* Privileged: */
// Will an object that inherits from this class be able to override the following functions?
// Or do I have to make these functions public in order to override them?
this.toString = function()
{
var s = "";
for (var attrib in attributeMap)
{
s += attrib + ": " + attributeMap[attrib] + ", ";
}
return s;
}
this.getType = function()
{
return attributeMap["type"];
}
this.renderObject = function()
{
// TODO: render object on HTML5 canvas
}
this.parseXMLNode = function( /*XML Node*/ nodeXML, /*string*/ objType )
{
var attribs = nodeXML.attributes;
for (var i=0; i<attribs.length; i++)
{
attributeMap[ attribs[i].nodeName ] = attribs[i].nodeValue;
}
// store children
if ( nodeXML.hasChildNodes() )
{
attributeMap["children"] = nodeXML.childNodes;
}
reformatObjectInnerHTML();
}
}
// Static Variables //
BaseObject.INSTANCE_COUNT = 0;
// My Child Class //
ChildClass.prototype = new BaseObject( objType ); // make ChildClass inherit from BaseClass
ChildClass.prototype.constructor = function(ObjType) // Make the ChildClass call the BaseClass constructor
{
BaseObject.prototype.constructor.call(this, objType);
}
function ChildClass( /*string*/ objType )
{
/* Privileged: */
// Attempt to override BaseClass function renderObject()
this.renderObject = function()
{
alert("ChildClass::renderObject();");
// Does this override the BaseClass renderObject() function?
}
}
How to Achieve Private, Public, Privileged members in Javascript
Though I'm not advising you to write code like this. JavaScript is different from C++. Don't write C++ code in JavaScript.
Seriously inheritance in JS is just not that useful. Copy the functions to another object if you need them there, are just call them in context of that object. I do plenty of OOP in Java land, but inheritance can easily be avoided in javascript through the use context and callbacks. That is if when you think you need an inheritance hierarchy, you probably just need a callback or call the function in a different context.
But to answer your question that is not the "correct" way check out javascript garden
function Foo() {
this.value = 42;
}
Foo.prototype = {
method: function() {}
};
function Bar() {}
// Set Bar's prototype to a new instance of Foo
Bar.prototype = new Foo();
Bar.prototype.foo = 'Hello World';
// Make sure to list Bar as the actual constructor
Bar.prototype.constructor = Bar;
var test = new Bar() // create a new bar instance

JavaScript class - Call method when object initialized

I have a class similar to the one below. How do I call my init method when the object is created? I don't want to have to create an instance of my object then call initialize like I do below.
var myObj = new myClass(2, true);
myObj.init();
function myClass(v1, v2)
{
// public vars
this.var1 = v1;
// private vars
var2 = v2;
// pub methods
this.init = function() {
// do some stuff
};
// private methods
someMethod = function() {
// do some private stuff
};
}
NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass instead of myClass.
Either you can call init from your constructor function:
var myObj = new MyClass(2, true);
function MyClass(v1, v2)
{
// ...
// pub methods
this.init = function() {
// do some stuff
};
// ...
this.init(); // <------------ added this
}
Or more simply you could just copy the body of the init function to the end of the constructor function. No need to actually have an init function at all if it's only called once.
There is even more smooth way to do this:
this.init = function(){
// method body
}();
This will both create method and call it.
See below for one possible answer, and some corrections to your code.
function myClass(v1, v2)
{
// public vars
this.var1 = v1;
// private vars
// use var to actually make this private
var var2 = v2;
// pub methods
this.init = function() {
// do some stuff
};
// private methods
// this will be private as though it had been declared with var
function someMethod() {
// do some private stuff
};
//call init
this.init();
}
JavaScript classes introduced in ECMAScript 2015 are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.
- MDN web docs
When using this syntax, because only the constructor() method is run on instantiation you can't auto-instantiate an object. You always have to add user = new MyUser()
var user;
class MyUser {
constructor(var1, var2) {
this.var1 = var1;
this.var2 = var2;
}
static staticMethod() {
// accessed directly with the class name `MyUser`
}
instanceMethod() {
// accessed with object instance
return true
}
}
user = new MyUser('hey','there')
Just add
this.init();
to your myClass function.

JavaScript: Public methods and prototypes

I'm not entirely sure how to implement OOP concepts in JS.
I have a class which is entirely declared in its constructor:
function AjaxList(settings)
{
// all these vars are of dubious necessity... could probably just use `settings` directly
var _jq_choice_selector = settings['choice_selector'];
var _jq_chosen_list = settings['chosen_list'];
var _cb_onRefresh = settings['on_refresh'];
var _url_all_choices = settings['url_choices'];
var _url_chosen = settings['url_chosen'];
var _url_delete_format = settings['url_delete_format'];
var jq_choice_selector_form = _jq_choice_selector.closest("form");
if (DEBUG && jq_choice_selector_form.length != 1)
{
throw("There was an error selecting the form for the choice selector.");
}
function refresh()
{
_updateChoicesSelector();
_updateChosenList();
_cb_onRefresh();
};
AjaxList.prototype.refresh = refresh; // will this be called on all AjaxLists, or just the instance used to call it?
// AjaxList.refresh = refresh; // will this be called on all AjaxLists, or just the instance used to call it?
// ...
}
There are multiple instances of AjaxList. When I call refresh() on one of them, I want only that one list to refresh itself. In the following instance:
term_list = AjaxList(settings);
term_list.refresh();
The refresh() call seems to make all the AjaxLists refresh themselves. What is the correct way to do this?
I'm using jQuery, if it makes any difference.
You should not redefine the prototype function in the constructor.
If you want to create a privileged function use this.methodname = ... from the constructor.
function AjaxList() {
var privateVar = 0;
function privateFunction() {
//...
}
//create a refresh function just for this instance of the AjaxList
this.refresh = function() {
//privileged function, it can access the 'privateVar & privateFunction'
privateVar++;
}
}
//public functions that don't need access to the private variables/functions
AjaxList.prototype.publicFunction=function() {
};
Also if you want to create a proper object, you need to change
term_list = AjaxList(settings);
to
term_list = new AjaxList(settings);
AjaxList = function(settings) {
this._jq_choice_selector = settings["choice_selector"];
this._jq_chosen_list = settings["chosen_list"];
this._cb_onRefresh = settings["on_refresh"];
this._url_all_choices = settings["url_choices"];
this._url_chosen = settings["url_chosen"];
this._url_delete_format = settings["url_delete_format"];
this.jq_choice_selector_form = _jq_choice_selector.closest("form");
if (DEBUG && jq_choice_selector_form.length != 1) {
throw "There was an error selecting the form for the choice selector.";
}
};
AjaxList.prototype = {
_updateChoicesSelector: function() { },
_updateChosenList: function() { },
_cb_onRefresh: function() { },
refresh: function() {
this._updateChoicesSelector();
this._updateChosenList();
this._cb_onRefresh();
}
};
Given that structure, you should be able to call:
var ajaxList = new AjaxList(settings);
ajaxList.refresh(); // etc.
I'm using jQuery, if it makes any
difference.
No it doesn't. See my answer here: What's the difference between Javascript, Jquery and Ajax?
I have a class which is entirely
declared in its constructor
There are no classes in Javascript. Forget them. You really need to learn some of the basics of this language in order to use them. It's not Java, even though it looks similar.
If you have a Constructor Function it will create an instance. The shared methods will be in the prototype chain, and only instance specific data goes right into the function with the this keyword.
So the basic concept of an object would look like this:
// constructor of an instance
function MyObject( param1, param2 ) {
this.param1 = param1;
this.param2 = param2;
this.param3 = 32;
return this; // [optional]
}
// Public methods can be called by any instance.
// Instances share their prototype object.
// The this keyword always points to the current
// instance that calls the method.
MyObject.prototype.sum = function() {
return this.param1 + this.param2 + this.param3;
}
// refresh should be a shared method, since it
// does the same thing on every instance
MyObject.prototype.refresh = function() {
// do the refresh
// ...
}
The power of this concept is that there is only one refresh function in memory. And it can deal with any instance. In addition, if another object inherits from MyObject the refresh function will be inherited. But in the memory there will be still one shared refresh function. And it can deal with any of the parent or child instances.

Inheritance of closure objects and overriding of methods

I need to extend a class, which is encapsulated in a closure. This base class is following:
var PageController = (function(){
// private static variable
var _current_view;
return function(request, new_view) {
...
// priveleged public function, which has access to the _current_view
this.execute = function() {
alert("PageController::execute");
}
}
})();
Inheritance is realised using the following function:
function extend(subClass, superClass){
var F = function(){
};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superclass = superClass.prototype;
StartController.cache = '';
if (superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
}
I subclass the PageController:
var StartController = function(request){
// calling the constructor of the super class
StartController.superclass.constructor.call(this, request, 'start-view');
}
// extending the objects
extend(StartController, PageController);
// overriding the PageController::execute
StartController.prototype.execute = function() {
alert('StartController::execute');
}
Inheritance is working. I can call every PageController's method from StartController's instance. However, method overriding doesn't work:
var startCont = new StartController();
startCont.execute();
alerts "PageController::execute".
How should I override this method?
It doesn't work because StartController calls PageController which adds an execute property to your object, so the execute property of StartController.prototype is not used.
For your overriding to work, you have to either :
1) define PageController.prototype.execute as the execute method of PageController. It won't work because then the function doesn't have access to _current_view.
2) define StartController.execute in the object constructor :
var StartController = function(request){
// calling the constructor of the super class
StartController.superclass.constructor.call(this, request, 'start-view');
// overriding the PageController::execute
this.execute = function() {
alert('StartController::execute');
}
}
// extending the objects
extend(StartController, PageController);
edit:
So you want for StartController.execute to access _current_view, which is impossible as long as _current_view is part of a closure that StartController is not part of. You might have to proceed like this:
(function () {
var _current_view;
window.PageController = function(request, new_view) {
...
this.execute = function() { ... }
}
window.StartController = function(request) {
StartController.superclass.constructor.call(this, request, 'start-view');
this.execute = function() { ... }
}
extend(StartController, PageController);
}()
var startCont = new StartController();
startCont.execute();
And if you want some kind of protected behavior, you might want to try this trick:
(function() {
var token = {};
window.Class1 = function() {
this.protectedMethod = function(tok) {
if(tok != token) return; // unauthorized
...
}
}
window.Class2 = function() {
new Class1().protectedMethod(token); // access granted
}
})()
new Class1().protectedMethod(); // access denied
There's no such thing as a package in javascript, so your possibilities are limited. You can certainly not have any kind of privileges among functions/objects/constructors that are not part of the same script. None that I know of, at least. Except maybe querying a server for some kind of authorization.

Categories