Out the following two ways, which format for defining object is good considering performance and usage:
//Object created with public members defined using this.
var object1 = function () {
var private_i = null;
this.public_j = null;
//public function
this.public_func = function () {
}
}
OR
//Object created with public members defined using return patterns.
var object2 = function () {
var private_i = null,
public_j = null,
//private function will be exposed from return statement.
_public_func = function () {
};
return {
public_func : _public_func
};
}
The difference between the two relates to inheritance and usage. Your object2 always creates objects directly backed by Object.prototype and doesn't require use of the new keyword; your object1 creates object backed by object1.prototype (which is in turn backed by Object.prototype) and does require use of new.
Neither is really "better" in any objective way, they are just two different ways of using JavaScript, which will have fundamentally the same performance. The first one is much more common, the second one is advocated by a small but vocal minority within the JavaScript community.
The object1 example is more typically written like this:
function Object1() {
var private_i = null;
this.public_j = null;
//public function
this.public_func = function () {
};
}
Note that the first letter in such functions is capitalized (by overwhelming convention).
The prototype thing comes into it if you're going to have functions that don't need access to private_i: You could put those on the object that will be assigned to new objects created via new Object1 like so:
function Object1() {
var private_i = null;
this.public_j = null;
//public function
this.public_func = function () {
};
}
Object1.prototype.someOtherFunction = function() {
// Doesn't use `private_i`
};
You can also use prototypes with your object2, like so:
//Object created with public members defined using return patterns.
var object2Prototype = {
someOtherFunction: function() {
// Doesn't need private_i
};
};
var object2 = function () {
var private_i = null,
public_j = null,
//private function will be exposed from return statement.
_public_func = function () {
};
var obj = Object.create(object2Prototype);
obj.public_func = _public_func;
return obj;
};
Related
Is there a name for describing the different ways you can define an object in Javascript?
There is this method which is more 'class-like' :
function MyObject() {
this.aMethod= new function(){
};
this.anotherMethod = new function(){
};
}
And this other technique which is more 'dynamic'.
MyObject = new Object();
MyObject.aMethod= new function(){
};
MyObject.anotherMethod = new function(){
};
I have been using both of these techniques in various ways, and i understand the benefits of each, but for the life of me, I don't have any idea how to call these two techniques when discussing this with colleauges.
Do these techniques have names?
In the first case MyObject is a constructor function, since it is supposed to be called with new:
var obj = new MyObject();
In the second case, MyObject is just an object and you assign properties to it. It does not have a special name.
Note that in both cases MyObject has different values. MyObject in the second case is equivalent to obj.
A third way is to use an object initilizer or "object literal":
var obj = {
aMethod: function(){},
anotherMethod: function(){}
};
Your first example is an Object Constructor, while the second is simply adding public methods as properties to an object. As a side note, for an even more "class-like" behavior take a look at the module pattern:
var MyObject = (function() {
var privateStaticVariable = 0;
var my = function() {
var self = this;
var privateInstanceVariable = 0;
function privateInstanceMethod() {
}
self.publicInstanceVariable = 0;
self.publicInstanceMethod = function() {
};
};
function privateStaticMethod() {
};
return my;
});
Say I have this code:
function ParentClass()
{
var anArray = [ ];
this.addToArray = function(what)
{
anArray.push(what);
console.log(anArray);
};
}
FirstSubClass.prototype = new ParentClass();
FirstSubClass.prototype.constructor = FirstSubClass;
function FirstSubClass()
{
this.addToArray('FirstSubClass');
}
SecondSubClass.prototype = new ParentClass();
SecondSubClass.prototype.constructor = SecondSubClass;
function SecondSubClass()
{
this.addToArray('SecondSubClass');
}
When I run new FirstSubClass() I see a single value array in the console. And when I run new SecondSubClass(), again, I see a single value array.
However, why is it when I run them again (i.e. new FirstSubClass(); new SecondSubClass();) I then see the arrays added to rather than new ones being created?
The rationale here is that I'm creating new instances of a class, therefore why are they sharing the same private property?
How can I avoid this so when I do, for e.g., new FirstSubClass() I then see a single value array no matter how many times I create a new instance of the class?
Keep in mind that you've only called new ParentClass() once for each subclass. That means that the private array variable is part of the prototype object for those subclasses. There's only one prototype object, so there's only one array (per subclass).
Each call to new FirstSubClass() generates a new instance that shares the same prototype object. The call to addToArray() therefore adds an element to that same array that was created when the prototype object was created.
edit — if you want per-instance arrays, you'd have to do something like this:
function ParentClass() {
this.addToArray = function(value) { this.instanceArray.push(value); };
};
function FirstSubClass() {
this.instanceArray = [];
this.addToArray("First");
}
FirstSubClass.prototype = new ParentClass();
FirstSubClass.prototype.constructor = FirstSubClass;
First, sub-classing in JS is typically a bad idea, because people think that they're getting extension, where every instance has its own copy of properties and methods...
...really, they're getting public static access to the parent's stuff.
Even better, that public static stuff has no access to the encapsulated variables, so there's really no manipulation of private data, unless you're using private functions (with a public interface) to pass data to and collect return values from, the public static stuff.
var Parent = function () {
this.static_prop = 0;
this.static_method = function (num) { this.static_prop += 1; return num + this.static_prop; };
};
var Child = function (num) {
this.public_func = function () { num = this.static_method(num); };
};
Child.prototype = new Parent();
var child = new Child(13);
child.public_func();
Just calling this.static_method wouldn't help, because it would have 0 access to num, which means that you're wrapping things which you inherited to grant them access to use private data as inputs, which means that you're doing most of the writing you'd be doing anyway, regardless of inheritance, because your expectations of .prototype were backwards.
Might I suggest Dependency Injection, instead?
Component-based programs?
var Iterator = function () {
var count = 0,
min = 0,
max = 0,
reset = function () { count = min; },
next = function () { count = count >= max ? min : count; return count += 1; },
set_min = function (val) { min = val; },
set_max = function (val) { max = val; },
public_interface = { reset : reset, count : count, set_min : set_min, set_max : set_max };
return public_interface;
},
Thing = function (iter) {
var arr = [],
currentObj = null,
nextObj = function () {
currentObj = arr[iter.next()];
},
add = function (obj) {
arr.push(obj); iter.set_max(arr.length);
},
public_interface = { next : nextObj, add : add };
return public_interface;
};
var thing = Thing(Iterator());
thing.add({});
thing.next();
It's a convoluted example, but now every instance is going to be given exactly what it needs to do its job (because the constructor requires it -- or you can add the dependency later, through a public method, or as a public-property).
The interfaces for each module can now also get as simple and as clean as you'd like, as you don't have to wrap unexpected static-helpers to get private data...
Now you know what's private, you know what you're extending to the public, and you have clean ins and outs wherever you want to put them.
You are only constructing a new instance of ParentClass once per subclass and that is to apply it to your prototype. If you want each instance to have its own copy of the private array and its own copy of the function "addToArray" you will need to invoke the ParentClass constructor function within your other objects constructors:
function ParentClass(){
var anArray = [ ];
this.addToArray = function(what){
anArray.push(what);
console.log(anArray);
};
}
FirstSubClass.prototype = new ParentClass();
FirstSubClass.prototype.constructor = FirstSubClass;
function FirstSubClass(){
//call the parents constructor where "this" points to your FirstSubClass instance
ParentClass.call( this );
this.addToArray('FirstSubClass');
}
SecondSubClass.prototype = new ParentClass();
SecondSubClass.prototype.constructor = SecondSubClass;
function SecondSubClass(){
ParentClass.call( this );
this.addToArray('SecondSubClass');
}
try this:
http://jsfiddle.net/3z5AX/2/
function ParentClass()
{
var anArray = [ ];
this.addToArray = function(what)
{
anArray.push(what);
document.getElementById("i").value = anArray;
};
}
//FirstSubClass.prototype = new ParentClass();
FirstSubClass.prototype.constructor = FirstSubClass;
function FirstSubClass()
{
this.parent = new ParentClass()
this.parent.addToArray('FirstSubClass');
}
var q = new FirstSubClass();
var r = new FirstSubClass();
All Subclasses share the same parent class, thus the same private anArray
The solution is to use the Mixin pattern.
// I have the habbit of starting a mixin with $
var $AddToArray = function(obj) {
var array = [];
obj.addToArray = function(what) {
array.push(what);
console.log(array);
};
}
var FirstClass = function() {
$AddToArray(this);
}
var SecondClass = function() {
$AddToArray(this);
}
How can i override this.property at runtime and for each instance, without making a new class and eventually calling doAnotherThing on the parent?
var ThridPartyObject = function() {
this.property = 'value';
this.doOneThing= function() { /* */ }
this.doAnotherThing= function() { /* */ }
};
No luck with:
ThridPartyObject.prototype = {
property: 'myvalue',
doOneThing: function() { // Override only this function and call the other
return this.doAnotherThing();
}
};
EDIT: forgot to say that property may or may not exists.
I need this because, in backbone.js, i have to define a custom property for all my model instances, and some function should act in a different way of original backbone ones. Here is how backbone defines a Backbone.Model (_.extend is from underscore.js):
var Model = Backbone.Model = function(attributes, options) {
var defaults;
attributes || (attributes = {});
if (options && options.collection) this.collection = options.collection;
if (options && options.parse) attributes = this.parse(attributes);
if (defaults = getValue(this, 'defaults')) {
attributes = _.extend({}, defaults, attributes);
}
this.attributes = {};
this._escapedAttributes = {};
this.cid = _.uniqueId('c');
this.changed = {};
this._silent = {};
this._pending = {};
this.set(attributes, {silent: true});
// Reset change tracking.
this.changed = {};
this._silent = {};
this._pending = {};
this._previousAttributes = _.clone(this.attributes);
this.initialize.apply(this, arguments);
};
// Attach all inheritable methods to the Model prototype.
_.extend(Model.prototype, Events, {
// cut
});
If the object is truly "third party," and outside your control, then the creators of it have chosen a pattern that is not compatible with prototypal inheritance (sometimes called the "closure pattern"). You will not be able to override, globally, any properties of ThirdPartyObject instances, because every ThirdPartyObject gets property, doOneThing, and doAnotherThing newly assigned to it at construction time.
In this case the only solution would be to create a new factory function wrapping the original:
function modifiedThirdPartyObjectFactory() {
var x = new ThirdPartyObject();
x.property = "myvalue";
return x;
}
var mtpo = modifiedThirdPartyObjectFactory();
A pattern that does use prototypal inheritance would work as follows:
function ThirdPartyObject() {
this.property = "value";
}
ThirdPartyObject.prototype.doOneThing = function () {
};
ThirdPartyObject.prototype.doAnotherThing = function () {
};
This pattern sets instance properties, usually data, in the constructor. Whereas shared properties, usually methods, go on the prototype. The original code made all properties instance properties, so there are no shared properties you can modify that would result in your changes being reflected across all instances.
You're actually thinking about it backwards.
Prototype would be like the parent class.
It's not exactly-like the parent class in a class-based language (there are a LOT of differences).
But in this instance, for the sake of inheriting properties/methods, prototype would be the parent class.
When you make a Foo, Foo is the child, for all intent and purpose in your problem.
When you do this:
function Foo () { this.method = function () {}; this.property = {}; }
Foo.prototype.method = function () {};
Foo.prototype.property = {};
Foo.prototype.other_property = 3;
It's similar to saying:
PrototypeClass {
public virtual property = {};
public other_property = 3;
public virtual method ( ) { }
}
Foo inherits BaseClass {
public override property = {};
public override method () {}
}
var foo = new Foo();
The constructor for Foo is overriding everything up the chain in the prototype, that has the same name.
When Foo doesn't have a method or a property inside of it, THEN it looks upstream, through its inheritance/prototype chain.
So if you want to override methods/properties of Foo, then you MUST override the instance of new Foo().
Your options for that are pretty much just to build a wrapper around Foo... ...like:
function FooPlusPlus () {
var foo = new Foo();
foo.plus = function () { this.doSomething(); console.log(this.val); };
foo.plusPlus = function () { foo.plus(); console.log(this.other_val); };
return foo;
}
var fooPlusPlus = FooPlusPlus(); // ***NO NEW***
...or to create a function which simply extends a pre-existing object (whether it's a "class" or a "dictionary" or a function, or an array) with whatever added properties/functionality you want to extend them with:
var extendObj = function (subject, extensions) {
var key = "";
for (key in extensions) { if (extension.hasOwnProperty(key)) {
subject[key] = extensions[key];
}}
}
var regularFoo = new Foo();
extendObj(regularFoo, { awesomeFunc : function () { if (typeof this.doSomething === "function") { this.doSomething(); }}, coolProp : "Bob" });
JS gives you the freedom to let anything inherit anything, as long as you aren't expecting strings or numbers to act like classes with custom data, without careful manipulation of the Core objects.
I came up with a simple design pattern that was inspired by several other design patterns. Its main purpose is to have private methods (instead of all global), methods visually nested and grouped within an object, and having "self" as an available variable to access the scope, which is really useful when using calling functions with a callback parameter.
It seems to work fine, but is it safe (performance - and scope-wise) to do Obj.apply(Obj);?
The code:
function Obj() {
var self = this;
var privateFunc = function() {
console.log('private');
self.otherPublic();
};
self.publicFunc = function() {
console.log('pub1ic');
privateFunc();
};
self.otherPublic = function() {
console.log('pub2');
};
} Obj.apply(Obj);
I call it like this:
Obj.publicFunc();
Totally pointless brother. What you're doing by Obj.apply(Obj); is taking the function Obj, and adding to it those methods, in an unintuitive manner.
This:
var Obj = (function(){
var priv = function(){ console.log('2'); },
privVar = 6;
return {
pub1: function(){ console.log('1'); },
pub2: function(){ priv(); }
};
})();
Does the same thing, although better. I say better because (1) it's intuitive, and (2) Obj is now a simple javascript object (typeof Obj === 'object') whereas your Obj is a function with properties augmented (typeof Obj === 'function').
If you want a reference to self it's not hard (although it seems unnecessary), just create the object which will be returned at the top of the function, and augment the public methods, either at the end, or as you make them...
It's safe, but pointless.
Also, note that these methods won't scale well, because for each instance of Obj we create each function is recreated, which is memory-wise wasteful. This pattern above is fine because we created it with an anonymous function, so by definition there can only be one instance, although for types you need to instantiate multiple times the prototype should be used.
Don't be scared of it, it's there to be helpful.
UPDATE:
var Obj = (function(){
var priv = function(){ pub2(); },
privVar = 6,
pub1 = function(){ priv(); },
pub2 = function(){ console.log('1'); };
return {
pub1: pub1,
pub2: pub2
};
})();
Obj.pub1();
Notice that I call a public function, which calls a private function, which calls a public function - no special binding, no object reference.
UPDATE 2:
var Obj = (function(){
var public = {},
priv = function(){ public.pub2(); },
privVar = 6;
public.pub1 = function(){ priv(); },
public.pub2 = function(){ console.log('1'); };
return public;
})();
Obj.pub1();
I have an existing class I need to convert so I can append functions like my_class.prototype.my_funcs.afucntion = function(){ alert(private_var);} after the main object definition. What's the best/easiest method for converting an existing class to use this method? Currently I have a JavaScript object constructed like this:
var my_class = function (){
var private_var = '';
var private_int = 0
var private_var2 = '';
[...]
var private_func1 = function(id) {
return document.getElementById(id);
};
var private_func2 = function(id) {
alert(id);
};
return{
public_func1: function(){
},
my_funcs: {
do_this: function{
},
do_that: function(){
}
}
}
}();
Unfortunately, currently, I need to dynamically add functions and methods to this object with PHP based on user selected settings, there could be no functions added or 50. This is making adding features very complicated because to add a my_class.my_funcs.afunction(); function, I have to add a PHP call inside the JS file so it can access the private variables, and it just makes everything so messy.
I want to be able to use the prototype method so I can clean out all of the PHP calls inside the main JS file.
Try declaring your "Class" like this:
var MyClass = function () {
// Private variables and functions
var privateVar = '',
privateNum = 0,
privateVar2 = '',
privateFn = function (arg) {
return arg + privateNum;
};
// Public variables and functions
this.publicVar = '';
this.publicNum = 0;
this.publicVar2 = '';
this.publicFn = function () {
return 'foo';
};
this.publicObject = {
'property': 'value',
'fn': function () {
return 'bar';
}
};
};
You can augment this object by adding properties to its prototype (but they won't be accessible unless you create an instance of this class)
MyClass.prototype.aFunction = function (arg1, arg2) {
return arg1 + arg2 + this.publicNum;
// Has access to public members of the current instance
};
Helpful?
Edit: Make sure you create an instance of MyClass or nothing will work properly.
// Correct
var instance = new MyClass();
instance.publicFn(); //-> 'foo'
// Incorrect
MyClass.publicFn(); //-> TypeError
Okay, so the way you're constructing a class is different than what I usually do, but I was able to get the below working:
var my_class = function() {
var fn = function() {
this.do_this = function() { alert("do this"); }
this.do_that = function() { alert("do that"); }
}
return {
public_func1: function() { alert("public func1"); },
fn: fn,
my_funcs: new fn()
}
}
var instance = new my_class();
instance.fn.prototype.do_something_else = function() {
alert("doing something else");
}
instance.my_funcs.do_something_else();
As to what's happening [Edited]:
I changed your my_funcs object to a private method 'fn'
I passed a reference to it to a similar name 'fn' in the return object instance so that you can prototype it.
I made my_funcs an instance of the private member fn so that it will be able to execute all of the fn methods
Hope it helps, - Kevin
Maybe I'm missing what it is you're trying to do, but can't you just assign the prototype to the instance once you create it? So, first create your prototype object:
proto = function(){
var proto_func = function() {
return 'new proto func';
};
return {proto_func: proto_func};
}();
Then use it:
instance = new my_class();
instance.prototype = proto;
alert(instance.prototype.proto_func());