I've been investigating multiple leveles of inheritance with "private" variable in each "class" in JavaScript, but run into this peculiar singularity:
function Ammo() {
var a = 0;
this.get_ammo = function() {
return a;
};
this.add_to_ammo = function() {
a = a+1
return a;
};
this.clean_ammo = function() {
return a=0;
}
}
function Weapon() {
var a =0;
}
function Gun() {
var a = 0;
this.fire = function(){
console.log("Bang");
}
}
Weapon.prototype = new Ammo();
Weapon.prototype.constructor = Weapon();
Gun.prototype = new Weapon();
Gun.prototype.constructor = Gun();
var a = new Ammo();
var w = new Weapon();
var g = new Gun();
a.add_to_ammo()
a.add_to_ammo()
a.add_to_ammo()
console.log(w.get_ammo())
// At this point I get 0, as expected. But after
w.add_to_ammo()
w.add_to_ammo()
w.add_to_ammo()
console.log(g.get_ammo())
// But here I get 3!
Can somebody explain why I get 3 after
console.log(g.get_ammo())
I thought that objects a, w, g are independent, so are their fields.
Also I found out that if I change
var a = 0;
to
this.a = 0;
I get expected result. fields of the object are unbound to their parents fields.
var a is defined in Ammo, but var a in the other constructors does absolutely nothing. The a that's being modified when you call the method no matter which instance is always the same a that was captured in the closure in Ammo.
You can't have private variables like you want in JavaScript, and that's ok. The most common way to do it is to make the variable public, and prefix it with an underscore, to mark it as "internal":
function Ammo() {
this._ammo = 0;
}
Then add the methods to the prototype and use this._ammo to reference that variable:
Ammo.prototype.getAmmo = function() {
return this._ammo
}
Then you can inherit with Object.create:
Weapon.prototype = Object.create(Ammo.prototype);
And in the constructor "call super":
function Weapon() {
Ammo.call(this) // gets own "_ammo"
}
Also, you are not setting up the constructor function properly. You should assign a function, not call it:
Weapon.prototype.constructor = Weapon;
Gun.prototype.constructor = Gun;
I don't have enough rep points to comment on #elclanrs answer, so forgive me.
His answer is all correct, but the most pertinent piece of information is the last
Also, you are not setting up the constructor function properly. You should assign a function, not call it:
Weapon.prototype.constructor = Weapon;
Gun.prototype.constructor = Gun;
your variables that are declared inside the scope of the function closure ARE IN FACT PRIVATE! however, you never properly instantiated you subclass objects, so you had a frankenstein thing going on: one object, lots of body parts.
Other than that there is nothing inherently wrong with your code, it's just not the way people usually write "Classes" and I won't explain why in the context of this question.
Related
I am quite new to javascript an trying to make sense of the basics. Coming from Python I am a bit overwhelmed by the different ways to get stuff done.
I came up with the pattern below to make constructors. I hope this is sound practice: is it? Some specific questions remain:
I jump to doing _this = this right away and only use _this. Is there any harm in that?
I allow the constructor to take an object as the first argument. The object properties become 'named parameters' and overwrite defaults. Any disadvantages to this?
Sorry that my questions aren't very specific, but I need a bit of confirmation/criticism at this stage.
var Omelette = function () {
var _this = this;
_this.publicName = 'Dexter';
_this.publicEggs = 6;
// Override property values with custom supplied values
// This comes after the default values and before they are used
for (var p in arguments[0]) {
_this[p] = arguments[0][p];
}
var privateGreeting = 'Hello, ';
_this.publicSayHi = function () {
console.log(privateGreeting + _this.publicName );
};
var privateBreakEggs = function (brokenEggs) {
_this.publicEggs = _this.publicEggs - brokenEggs;
};
// initializing the prototype breaks two eggs
privateBreakEggs(2);
console.log(_this.publicEggs);
};
var myOmelette = new Omelette({
publicName: 'Roy'
});
// 4
var hisOmelette = new Omelette({
publicEggs: 12
});
// 10
hisOmelette.publicSayHi();
// Hello Dexter
hisOmelette.publicEggs = 12;
// No more eggs are broken
console.log(myOmelette.publicEggs);
// These are unchanged
hisOmelette.breakEggs();
// not publicly accessible. error 'undefined is not a function'
Take a look at the following code:
var Omelette = function (overrideObject) {
this.publicName = 'Dexter';
this.publicEggs = 6;
// Override property values with custom supplied values
if (overrideObject)
{
var keys = Object.keys(overrideObject); //get all the keys from the override object.
//We use Object.keys for this. -> puts all the keys of an object into an array.
for (var i = 0; i < keys.length; ++i)
{
this[keys[i]] = overrideObject[keys[i]]; //loop over every key and overwrite/set the value a public variable.
}
}
var privateGreeting = 'Hello, ';
this.publicSayHi = function () {
console.log(privateGreeting + this.publicName ); //this refers to the instance created and the owner of function publicSayHi.
};
var privateBreakEggs = function (brokenEggs) {
this.publicEggs = this.publicEggs - brokenEggs;
};
this.breakEggs = privateBreakEggs; //reference to privateBreakEggs, making it publically available.
//this won't work since the this in privateBreakEggs refers to its own scope.
privateBreakEggs(2);
//this will work since it's called via `this`.
this.breakEggs(2);
};
var myOmelette = new Omelette({
publicName: 'Roy'
});
myOmelette.publicSayHi(); //should say Roy.
var hisOmelette = new Omelette({
publicEggs: 12
});
hisOmelette.publicSayHi(); //should say Dexter
console.log(hisOmelette.publicEggs); //10
console.log(myOmelette.publicEggs); //4
// These are unchanged
hisOmelette.breakEggs(2); //eggs now 8
console.log(hisOmelette.publicEggs)
hisOmelette.privateBreakEggs
// not publicly accessible. 'undefined'
I've made several changes to your code and commented. Compare it with your own code and learn from the differences. I'm no longer introducing the _this variable, since it's unnecessary.
There are no real disadvantages to override the default properties of an instance using an argument. The could be added to the instance after it's created, now they are added during creation. Your method (improved by me) allows for easy creation of properties on the creation of the instance. Bear in mind that the properties are only set on that instance. If you want them to be shared with all the instances use a prototype.
I found different ways that seem to work.
Mostly recommended way in textbooks and the internet:
var Person = function() {
this.age = 23;
}
Tony = new Person();
This also seems to work:
function Person() {
this.age = 23;
}
Tony = new Person();
Is there a difference? And an additional question: Usually you cannot simply leave out parentheses. Here it is possible (new Person instead of new Person()). This is because of using the new keyword, right?
A third odd way that I just tried out looks like this:
function Person() {
return {age: 2};
}
Tony = new Person();
Tony = Person(); // both ways work! It seems that you can leave out 'new' here.
Here I don't get an object with the name of my class, but my property is also accessible and it seems like it was quite similar to both above approaches.
What shall I use and what are the technical differences? Thank you!
JavaScript is a classless language. Classes don't exist, but objects may inherit properties from each other by using prototypes. This means you are not limited to implementing inheritance in a class-like manner. Personally, I like to use a BackboneJS-inspired method (code requires UnderscoreJS):
var BaseObject = function(){}; //Create a function so that we may use the new operator.
//There may be code in the constructor
BaseObject.extend = function(obj) { //Add a static function to the BaseObject to extend it
var base = this; //Save a reference for later
//Create the constructor for the sub object. We need to extend it, so we can't use the base constructor. AFAIK, this is the only way to clone the base constructor, i.e. by creating a new function that calls it
var SubObject = _.extend(function(){
base.apply(this, arguments); //Call base constructor
}, this);
SubObject.prototype= _.extend({}, this.prototype, obj); //Create new prototype that extends the super prototype, but does not overwrite it.
return SubObject; //Return the new constructor + prototype
};
This allows you to do cool class-like stuff like this:
var Car = BaseObject.extend({
speed: 0,
acceleration: 5,
accelerate: function(){
this.speed += this.acceleration;
}
});
var RaceCar = Car.extend({
acceleration: 10,
});
var car = new Car();
var raceCar = new RaceCar();
car.accelerate();
raceCar.accelerate();
if(raceCar.speed > car.speed){
console.log('raceCar won');
}else{
console.log('car won');
}
For more information on inheritance in JavaScript, I strongly recommend reading JavaScript: The Good Parts by Douglas Crockford.
Regarding your examples:
The difference between 1 and 2 is minimal. For more information see this question.
In 3, you are just returning an object literal. The new keyword only has influence on the this keyword within the function, which you are not using, and so using new has no effect. For more information, see this quesion
1 and 2 (var x = function vs function x) are very similar. 3 is a completely different thing.
The difference between 1 and 2 has nothing to do with classes and has been asked before on SO (several times). I think the most complete answer is this one:
https://stackoverflow.com/a/338053/1669279
In short, the first x points to an anonymous function and some debugging tools might have problems with that. The first one is available from the line it was defined on while the second is available in the entire scope. Read the linked answer for details.
The 3rd "solution" is not a class at all. It is simply a function that returns an object (might be called a Factory method).
It is not a good idea to return things from your constructors, especially return this. You should only return things if you want to override the normal process of creating objects (like implementing the singleton pattern for example).
As a side-note, you should always use new when you instantiate a class. Here is what happens when you try to be smart and save characters:
function X () {
return this;
}
console.log(X()); // outputs the window object
The parenthesis after calling the constructor with no parameters are optional, but it is frowned upon to avoid them because it results in slightly more confusing code.
To sum it up, i usually use pattern 1. Pattern 2 is also ok.
One problem with pattern 2 can be this one:
var x = new X(); // works
console.log(x.message); // works, I am X
x.method(); // doesn't work, method hasn't been defined yet
function X() {
this.message = 'I am X';
}
X.prototype.method = function() {
console.log(this.message);
};
this is how i do mine:
;(function (window) {
"use strict";
//-- Private Vars
var opt, obj, rm, Debug;
//-- construtor
function App(requestedMethod) {
//-- set up some vars
if(typeof requestedMethod !== 'undefined') {
rm = requestedMethod;
}
opt = {
rMethod: (typeof rm !== 'undefined') ? (rm != null) ? rm : false : false
}
//-- containe resulable objects
obj = {}
//-- call the init method
this.init();
}
/** Public Methods **/
/**
* The Init method called on every page load
*/
App.prototype.init = function () {
var om = opt.rMethod;
//-- Once all init settings are performed call the requested method if required
if(om) {(typeof App.prototype[om] == 'function') ? App.prototype[om]() : _DB('Call to Method [' + om + '] does not exsist.');}
};
/**
* testmethod
*/
App.prototype.testmethod = function () {
};
/** Private Methods **/
function PrivateMethod(){
}
/**
* A console output that should enable to remain enable js to work in IE
* just incase i forget to remove it when checking on those pesky IE browsers....
*/
function _DB(msg){
if(window.console && window.console.log){
var logDate = new Date();
window.console.log('------------------- ' + logDate + ' ----------------------------------');
window.console.log(msg);
}
};
window.App = App;
})(window);
then call it like:
<script src="ptha/to/your/app.js"></script>
<script>$(function() { new App('testmethod'); });</script>
When the code is loaded the new App() will then run once all page load data has completed
Hope this helps.To get access to it outside add the new to a var
var App = new App('testmethod);
then you can access things like
App.testmethod()...
var Person = function() {
this.age = 23;
}
Person is a variable that contains(is referenced) an anonymous function
function Person() {
this.age = 23;
}
but here you declare a function called "Person"
function Person() {
return {age: 2};
}
and so you declare a function that returns a new static object.
The best way depends on the needs, if you want to declare classes use the second, while to create the modules uses the third. For the first method look here: http://helephant.com/2008/08/23/javascript-anonymous-functions/
I am new to pseudo classes and prototypes in JavaScript and I am having a bit of difficulty implementing it properly. What I am trying to do is have a base 'class' with some fields then create a prototype of that base class with my methods defined as object literals. I am torn between doing it this way and just using singletons inside my base class for my methods. I think though that doing it this way is a little more elegant and I think I am actually not creating every method every time I create a new object.
Anyways, the small issue I am having is referencing the fields of my base class in my methods. Because when I try to reference them as this.field this is referring to the current function/ scope but I want it to reference the newly create object. Is there a work around for this or should I change the way I am creating my methods.
Below is some code that I think will make it more clear what I am doing and the problem I am having.
function BaseClass() {
this.items[];
this.fieldOne = "asdasd";
}
BaseClass.prototype = {
methodOne: function (input) {
function addElement(a. b) {
var element = {};
element.prop1 = a;
element.prop2 = b;
//The issue I am having is that items is undefined, how can I refernce the parent class object.
this.items.push(element);
}
function traverse() {
//go through a list and add a bunch of elements
addElement("ASdasd", 324);
}
},
methodTwo: function () {
//see now fieldOne is asdasd
console.log("fieldOne" + fieldOne);
}
}
var forTest = new BaseClass();
forTest.methodTwo();
So yeah I want to have some fields in the parent class that I can access from any method, but I would rather not just put the functions in my base class so that I do not create every method everytime I create a new object from BaseClass. Is there a work around or a better way to implement this?
Thanks in advance for the help.
You're losing the reference to this inside your nested functions. You can solve that with:
methodOne: function (input) {
var self = this;
function addElement(a. b) {
var element = {};
element.prop1 = a;
element.prop2 = b;
//The issue I am having is that items is undefined, how can I refernce the parent class object.
self.items.push(element);
}
function traverse() {
//go through a list and add a bunch of elements
addElement("ASdasd", 324);
}
// You never called anything?
// is traverse() what you wanted?
traverse();
},
methodOne: function (input) {
function addElement(a. b) {
var element = {};
element.prop1 = a;
element.prop2 = b;
//The issue I am having is that items is undefined, how can I refernce the parent class object.
this.items.push(element);
}
The issue here is that you've encountered javascript design error which is that this in subfunction is bound to wrong object. The ususal workaround for this looks like:
methodOne: function (input) {
var that = this;
function addElement(a, b) {
...
that.items.push(element);
}
}
In fact it's bound to the global object:
var o = {
f : function(){
var g = function(){
this.name = "test";
};
g();
}
};
o.f();
console.log(name); // "test"
This is my first stab at OOP, so please bear with me:
(function(){
var Ship = function(){
this.passengers = [];
this.hasAliens = function() {
return this.passengers.some(function(passenger){
return passenger.isAlien()
});
}
};
var Passenger = function(){};
Passenger.prototype.isAlien = function(){
return this instanceof Alien;
};
Passenger.prototype.board = function(ship) {
ship.passengers.push(this)
}
var Alien = function() { Passenger.call(this); }
var Human = function() { Passenger.call(this); }
Alien.prototype = Object.create(Passenger.prototype);
Human.prototype = Object.create(Passenger.prototype);
Alien.prototype.constructor = Alien.constructor;
Human.prototype.constructor = Human.constructor;
var ship = new Ship();
var john = new Human();
var zorg = new Alien();
//simple testing
john.board(ship);
console.log("Ship does not have aliens ", ship.hasAliens()===false);
zorg.board(ship);
console.log("Ship has aliens ", ship.hasAliens()===true);
})();
This works fine. However, I'd like to know how to pass the Passenger.isAlien() method to save me that nasty nested anonymous function. I'm trying to do it like this:
var Ship = function(){
this.passengers = [];
this.hasAliens = function(){
return this.passengers.some(Passenger.isAlien);
};
};
But that gives me "undefined is not a function"
http://jsfiddle.net/WYyxY/
As I said, isAlien is a property of the prototype, i.e. an instance of the constructor function, and not the constructor function itself. Passenger.isAlien is indeed undefined (nowhere in your code is Passenger.isAlien = function....).
There is not really a more concise way to do this. Think about what a callback passed to .some is doing: It has to take an element of the array as argument and then do something with it. In your case you want to execute a method of that element.
One way to call a method and pass the object it should be called on as parameter is to use .call [MDN]. Unfortunately, as with all functions in JavaScript, you cannot just get a reference to Passenger.prototype.isAlien.call, because .call looses its context (it does not know which function it refers to). You'd have to bind it to Passenger.prototype.isAlien first
this.passengers.some(
Passenger.prototype.isAlien.call.bind(Passenger.prototype.isAlien)
);
and personally I find that not more readable.
Stick with the anonymous function, your intend is much clearer. Or if you want to, you can let another function create that function:
function callOn(funcName) {
return function(obj) {
return obj[funcName]();
};
}
this.passengers.some(callOn('isAlien'));
For doing OOP with javascript, I strongly recommend checking out prototypeJS. Your code becomes much more readable, and it also supports inheritance!
Here's a quick look at it
In JavaScript I see a few different ways, certain tasks can be performed within an object for example, the object Egg I have below.
Can anyone tell me the difference between each one, why I would use one and not the other etc
var Egg = function(){
//Properties
var shell = "cracked" // private property
this.shell = "cracked" // public property
shell: "cracked" // what is this??
//functions
function cook(){
//standard function
}
cook: function(){
//what kind of function is this?
}
//not sure what this is
details: {
//What is this? an array :S it holds 2 elements?
cost: 1.23,
make: 'Happy Egg';
}
}
Your code snippet isn't quite valid, but here are a few things it raises:
Property initializers, object initializers
You've asked what shell: cracked is. It's a property initializer. You find them in object initializers (aka "object literals"), which are written like this:
var obj = {
propName: "propValue"
};
That's equivalent to:
var obj = {};
obj.propName = "propValue";
Both of the above create an object with a property called propName which has a string value "propValue". Note that this doesn't come into it.
Functions
There are a couple of places where functions typically come into it vis-a-vis objects:
Constructor functions
There are constructor functions, which are functions you call via the new operator. Here's an example:
// Constructor function
function Foo(name) {
this.name = name;
}
// Usage
var f = new Foo("Fred");
Note the use of the keyword this in there. That's where you've seen that (most likely). When you call a constructor function via new, this refers to the new object created by the new operator.
this is a slippery concept in JavaScript (and completely different from this in C++, Java, or C#), I recommend these two (cough) posts on my blog:
You must remember this
Mythical methods
Builder/factory functions
You don't have to use constructor functions and new, another pattern uses "builder" or "factory" functions instead:
// A factory function
function fooFactory(name) {
var rv = {}; // A new, blank object
rv.name = name;
return rv;
}
// Usage
var f = fooFactory("Fred");
Private properties
You mentioned "private" properties in your question. JavaScript doesn't have private properties at all (yet, they're on their way). But you see people simulate them, by defining functions they use on the object as closures over an execution context (typically a call to a constructor function or a factory function) which contains variables no one else can see, like this:
// Constructor function
function EverUpwards() {
var counter = 0;
this.increment = function() {
return ++counter;
};
}
// Usage:
var e = new EverUpwards();
console.log(e.increment()); // "1"
console.log(e.increment()); // "2"
(That example uses a constructor function, but you can do the same thing with a factory function.)
Note that even though the function we assign to increment can access counter, nothing else can. So counter is effectively a private property. This is because the function is a closure. More: Closures are not complicated
Sure, Ben.
This sort of gets to the bottom of the dynamism of JavaScript.
First, we'll look at basics -- if you're coming from a place where you understand class-based languages, like, say, Java or C++/C#, the one that is going to make the most sense is the constructor pattern which was included very early on:
function Egg (type, radius, height, weight) {
// private properties (can also have private functions)
var cost = (type === "ostrich") ? 2.05 * weight : 0.35 * weight;
// public properties
this.type = type;
this.radius = radius;
this.height = height;
this.weight = weight;
this.cracked = false;
// this is a public function which has access to private variables of the instance
this.getCost = function () { return cost; };
}
// this is a method which ALL eggs inherit, which can manipulate "this" properly
// but it has ***NO*** access to private properties of the instance
Egg.prototype.Crack = function () { this.cracked = true; };
var myEgg = new Egg("chicken", 2, 3, 500);
myEgg.cost; // undefined
myEgg.Crack();
myEgg.cracked; // true
That's fine, but sometimes there are easier ways of getting around things.
Sometimes you really don't need a class.
What if you just wanted to use one egg, ever, because that's all your recipe called for?
var myEgg = {}; // equals a new object
myEgg.type = "ostrich";
myEgg.cost = "......";
myEgg.Crack = function () { this.cracked = true; };
That's great, but there's still a lot of repetition there.
var myEgg = {
type : "ostrich",
cost : "......",
Crack : function () { this.cracked = true; }
};
Both of the two "myEgg" objects are exactly the same.
The problem here is that EVERY property and EVERY method of myEgg is 100% public to anybody.
The solution to that is immediately-invoking functions:
// have a quick look at the bottom of the function, and see that it calls itself
// with parens "()" as soon as it's defined
var myEgg = (function () {
// we now have private properties again!
var cost, type, weight, cracked, Crack, //.......
// this will be returned to the outside var, "myEgg", as the PUBLIC interface
myReturnObject = {
type : type,
weight : weight,
Crack : Crack, // added benefit -- "cracked" is now private and tamper-proof
// this is how JS can handle virtual-wallets, for example
// just don't actually build a financial-institution around client-side code...
GetSaleValue : function () { return (cracked) ? 0 : cost; }
};
return myReturnObject;
}());
myEgg.GetSaleValue(); // returns the value of private "cost"
myEgg.Crack();
myEgg.cracked // undefined ("cracked" is locked away as private)
myEgg.GetSaleValue(); // returns 0, because "cracked" is true
Hope that's a decent start.
You are mixing syntaxes between object property declaration and simple javascript statements.
// declare an object named someObject with one property
var someObject = {
key: value
};
// declare an anonymous function with some statements in it
// and assign that to a variable named "someFunction"
var someFunction = function () {
// any javascript statements or expressions can go here
};
There's a key distinction in JavaScript between objects and functions. Objects hold a bunch of data (including functions), and functions can be used to make or modify objects, but they aren't inherently the same thing. OOP in JavaScript is based around using functions as classes. For example, take the following class:
Test = function(){
this.value = 5;
}
If you just call the function Test(), then nothing will happen. Even if you say var x = Test(), the value of x will be undefined. However, using the new keyword, magic happens! So if we say var x = new Test(), then now the variable x will contain a Test object. If you do console.log(x.value), it would print 5.
That's how we can use functions to make objects. There's also a key different in syntax--a function can contain any sort of JavaScript block you want, whether that's if statements or for loops or what have you. When declaring an object, though, you have to use the key: value syntax.
Hope that clears things up a little bit!