Javascript objects inheritance - javascript

I am working on a project whereby i have noticed there are multiple references to the same objects in different areas. But i have been reading on mixins and just prototypal inheritance but not sure which one to follow:
So my current objects look like below but i need for product to inherit the base class including the function which is used everytime.
var base = function() {
this.id = 0;
this.refererer = null;
this.getCurrency = function() {
return "US"
}
}
var product = function() {
this.name = "";
this.description = "";
}
How can i implement the above to use either mixins or prototypal inheritance?

var base = function() {
this.id = 0;
this.refererer = null;
this.getCurrency = function() {
return "US"
}
}
var product = function() {
this.name = "";
this.description = "";
}
product.prototype = new base(); // this will do the inheritance trick
product.prototype.constructor = product;
var proObj = new product();
alert(proObj.id); // 0 base class property "id"

Related

for (var o in this) inside an object

I’ve made a little sandbox using the p5.js library : http://gosuness.free.fr/balls/
I’m trying to implement a way to deal with the options on the side, which are toggled using keyboard shortcuts.
This is what I tried to do :
var options =
{
Option: function(name, value, shortcut)
{
this.name = name;
this.shortcut = shortcut;
this.value = value;
this.show = function ()
{
var texte = createElement("span",this.name + " : " + this.shortcut + "<br />");
texte.parent("options");
texte.id(this.name);
}
},
toggle: function(shortcut)
{
for (var o in this)
{
console.log(o);
if (o.shortcut == shortcut)
{
o.value = !o.value;
changeSideText("#gravity",gravity);
addText("Toggled gravity");
}
}
}
};
I instantiate each option inside the object options thus :
var gravity = new options.Option("gravity", false,"G");
var paintBackground = new options.Option("paintBackground",false,"P");
When I call the function options.toggle, console.log(o) gives me "Option" "toggle". but what I want is to get for (var o in this) to give me the list of properties of the object options, which are in this case gravity and paintBackground
How do I do that ?
Thanks !
When You create a instance of Option, its not kept within the variable options, but in the provided variable.
var gravity = new options.Option("gravity", false,"G");
Creates an instance of Option located under gravity variable.
Your iterator for (var o in this) iterates over options properties, with the correct output of the object's methods.
If You want your code to store the new instances of Option within options variable, you can modify code like
var options =
{
instances: [],
Option: function(name, value, shortcut)
{
this.name = name;
this.shortcut = shortcut;
this.value = value;
this.show = function ()
{
var texte = createElement("span",this.name + " : " + this.shortcut + "<br />");
texte.parent("options");
texte.id(this.name);
}
options.instances.push(this);
},
toggle: function(shortcut)
{
for (var i in this.instances)
{
console.log(this.instances[i]);
if (this.instances[i].shortcut == shortcut)
{
this.instances[i].value = !this.instances[i].value;
changeSideText("#gravity",gravity);
addText("Toggled gravity");
}
}
}
};
this is your example working as You intend it to, but i wouldnt consider this as a reliable design pattern.

Auto increment value in javascript class

I'm trying to auto increment a properties value each time I instantiate a new instance of the class. This is what my class constructor looks (I abstracted it down just a bit):
var Playlist = function(player, args){
var that = this;
this.id = ?; //Should auto increment
this.tracks = [];
this.ready = false;
this.unloaded = args.length;
this.callback = undefined;
this.onready = function(c){
that.callback = c;
};
this.add = function(tracks){
for(var i = 0; i < tracks.length; i++){
this.tracks.push(tracks[i]);
this.resolve(i);
}
};
this.resolve = function(i){
SC.resolve(that.tracks[i]).then(function(data){
that.tracks[i] = data;
if(that.unloaded > 0){
that.unloaded--;
if(that.unloaded === 0){
that.ready = true;
that.callback();
}
}
});
};
player.playlists.push(this);
return this.add(args);
};
var playlist1 = new Playlist(player, [url1,url2...]); //Should be ID 0
var playlist2 = new Playlist(player, [url1,url2...]); //Should be ID 1
I'd like to not define an initial variable that I increment in the global scope. Could anyone hint me in the right direction? Cheers!
You can use an IIFE to create a private variable that you can increment.
var Playlist = (function() {
var nextID = 0;
return function(player, args) {
this.id = nextID++;
...
};
})();
You can set Playlist.id = 0 somewhere in your code, then increment it in the constructor and assign the new value to the instance property, as: this.id = Playlist.id++.
This suffers from the fact that it is not well encapsulated, so it could be misused.
Otherwise, I was to propose the solution described by Mike C, but he already set a good answer that contains such an idea, so...

javascript constructors involving unknown amounts of arguments...

I was messing with some js on codecadamy and got a bit sidetracked trying to make something work.
In essence I was creating a few objects that are loaded into a controller object and set as properties of it with two functions that print the properties and compare a string to the name property of each object in the controller.
I noticed I can do it if I make the objects in the prototype style and specify a normal function to handle setting the properties like so:
var friends = {};
friends.setUp = function() {
this.friends = [];
for(var i in arguments) {
arguments[i].setUp();
this.friends.push(arguments[i]);
}
};
friends.list = function() {
for(var i in this.friends) {
console.log(this.friends[i]);
}
};
friends.search = function(name) {
for(var i in this.friends) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
var bill = {};
bill.setUp = function() {
this.firstName = "Bill";
this.lastName = "Gates";
this.number = "(206) 555-5555";
this.address = ['One Microsoft Way','Redmond','WA','98052'];
};
var steve = {};
steve.setUp = function() {
this.firstName = "Steve";
this.lastName = "Jobs";
this.number = "(206) 555-5555";
this.address = ['1 Infinite Loop','Cupertino','CA','95014'];
};
var mike = {};
mike.setUp = function() {
this.firstname = "Mike";
this.lastname = "Ryd";
this.number = "(800) 555-5555";
this.address = ['redacted'];
};
friends.setUp(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
However if I do it with constructors It does not work, example:
function bill() {
this.firstName = "Bill";
this.lastName = "Gates";
this.number = "(206) 555-5555";
this.address = ['One Microsoft Way','Redmond','WA','98052'];
};
function steve() {
this.firstName = "Steve";
this.lastName = "Jobs";
this.number = "(206) 555-5555";
this.address = ['1 Infinite Loop','Cupertino','CA','95014'];
};
function mike() {
this.firstname = "Mike";
this.lastname = "Ryd";
this.number = "(800) 555-5555";
this.address = ['redacted'];
};
function friends() {
this.friends = [];
for(var i in arguments) {
this.friends.push(arguments[i]);
}
};
friends.list = function() {
for(var i in this.friends) {
console.log(this.friends[i]);
}
};
friends.search = function(name) {
for(var i in this.friends) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
var bill = new bill();
var steve = new steve();
var mike = new mike();
var friends = new friends(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
I was wondering if this is a limitation of using constructors or am I messing up the syntax somewhere? Thank you!
This doesn't appear to have anything to do with constructors with an unknown number of arguments, but rather you are not assigning methods on your objects appropriately. They need to be put on the prototype so that they will be inherited by all objects that are created by this particular constructor. So in your code, these:
friends.list = function() {...}
friends.search = function() {...}
needs to be changed to:
friends.prototype.list = function() {...}
friends.prototype.search = function() {...}
Like this:
friends.prototype.list = function() {
for(var i = 0; i < this.friends.length; i++) {
console.log(this.friends[i]);
}
};
friends.prototype.search = function(name) {
for(var i = 0; i < this.friends.length; i++) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
Then, this code should work fine:
var bill = new bill();
var steve = new steve();
var mike = new mike();
var friends = new friends(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
And, then the code works as you would expect here: http://jsfiddle.net/jfriend00/ba4me8ua/
FYI, you'll noticed that I changed the way you iterate through the arguments object items to be more array-like and avoid any chance of getting any non-numeric properties in the iteration.

Javascript: Modify an object from a pointer

I'm making a digital library with three classes: Library, Shelf & Book. Shelves have their contents as an array of books. Books have two methods, enshelf and unshelf. When a book gets unshelfed it's supposed to set delete the instance of itself from the shelf it's on and then set it's location property to null. How can I modify the shelf it's sitting on? In the constructor if I change this.location, it will just give that property a new value instead of modifying the variable it points to. I feel like this is really simple and I'm overlooking something super basic.
var _ = require('lodash');
//books
var oldMan = new Book("Old Man and the Sea", "Ernest Hemingway", 0684801221);
var grapes = new Book("The Grapes of Wrath", "John Steinbeck", 0241952476);
var diamondAge = new Book("The Diamond Age", "Neal Stephenson", 0324249248);
//shelves
var shelf0 = new Shelf(0);
var shelf1 = new Shelf(1);
//libraries
var myLibrary = new Library([shelf0, shelf1], "123 Fake Street");
//these need to accept an unlimited amount of each
function Library(shelves, address) {
this.shelves = shelves; //shelves is an array
this.address = address;
this.getAllBooks = function() {
console.log("Here are all the books in the library: ");
for (var i = 0; i < this.shelves.length; i++) {
console.log("Shelf number " + i + ": ");
for (var j = 0; j < this.shelves[i].contents.length; j++) {
console.log(this.shelves[i].contents[j].name);
}
}
}
}
function Shelf(id) {
this.id = id;
this.contents = [];
}
function Book(name, author, isbn) {
this.name = name;
this.author = author;
this.isbn = isbn;
this.location = null;
this.enshelf = function(newLocation) {
this.location = newLocation;
newLocation.contents.push(this);
}
this.unshelf = function() {
_.without(this.location, this.name); //this doesn't work
this.location = null;
}
}
console.log("Welcome to Digital Library 0.1!");
oldMan.enshelf(shelf1);
myLibrary.getAllBooks();
oldMan.unshelf();
myLibrary.getAllBooks();
Small issue with your unshelf method, easily remedied:
this.unshelf = function() {
this.location.contents =
_.without(this.location.contents, this);
this.location = null;
}
Consider, however, that shelf and unshelf should be methods of Shelf, and not of Book. Also, if you must have this method, surround it with a guard, like so:
this.unshelf = function() {
if (this.location) {
this.location.contents =
_.without(this.location.contents, this);
this.location = null;
}
}
Couple of small issues:
without works on arrays and returns a copy of the array with the elements removed - the original is untouched. So you need to pass location.contents instead of just location and reassign it back to location.contents.
Also you add the whole book to the Shelf, then try to remove it by name, so it doesn't match and get removed. So just pass this to without:
this.unshelf = function() {
if (this.location) {
this.location.contents = _.without(this.location.contents, this);
this.location = null;
}
}

Javascript "private" vs. instance properties

I'm doing some Javascript R&D and, while I've read Javascript: The Definitive Guide and Javascript Object Oriented Programming, I'm still having minor issues getting my head out of class based OOP and into lexical, object based OOP.
I love modules. Namespaces, subclasses and interfaces. w00t. Here's what I'm playing with:
var Classes = {
_proto : {
whatAreYou : function(){
return this.name;
}
},
Globe : function(){
this.name = "Globe"
},
Umbrella : new function(){
this.name = "Umbrella"
}(),
Igloo : function(){
function Igloo(madeOf){
this.name = "Igloo"
_material = madeOf;
}
// Igloo specific
Igloo.prototype = {
getMaterial : function(){
return _material;
}
}
// the rest
for(var p in Classes._proto){
Igloo.prototype[p] = Classes._proto[p]
}
return new Igloo(arguments[0]);
},
House : function(){
function House(){
this.name = "My House"
}
House.prototype = Classes._proto
return new House()
}
}
Classes.Globe.prototype = Classes._proto
Classes.Umbrella.prototype = Classes._proto
$(document).ready(function(){
var globe, umb, igloo, house;
globe = new Classes.Globe();
umb = Classes.Umbrella;
igloo = new Classes.Igloo("Ice");
house = new Classes.House();
var objects = [globe, umb, igloo, house]
for(var i = 0, len = objects.length; i < len; i++){
var me = objects[i];
if("whatAreYou" in me){
console.log(me.whatAreYou())
}else{
console.warn("unavailable")
}
}
})
Im trying to find the best way to modularize my code (and understand prototyping) and separate everything out. Notice Globe is a function that needs to be instantiated with new, Umbrella is a singleton and already declared, Igloo uses something I thought about at work today, and seems to be working as well as I'd hoped, and House is another Iglooesque function for testing.
The output of this is:
Globe
unavailable
Igloo
My House
So far so good. The Globe prototype has to be declared outside the Classes object for syntax reasons, Umbrella can't accept due to it already existing (or instantiated or... dunno the "right" term for this one), and Igloo has some closure that declares it for you.
HOWEVER...
If I were to change it to:
var Classes = {
_proto : {
whatAreYou : function(){
return _name;
}
},
Globe : function(){
_name = "Globe"
},
Umbrella : new function(){
_name = "Umbrella"
}(),
Igloo : function(){
function Igloo(madeOf){
_name = "Igloo"
_material = madeOf;
}
// Igloo specific
Igloo.prototype = {
getMaterial : function(){
return _material;
}
}
// the rest
for(var p in Classes._proto){
Igloo.prototype[p] = Classes._proto[p]
}
return new Igloo(arguments[0]);
},
House : function(){
function House(){
_name = "My House"
}
House.prototype = Classes._proto
return new House()
}
}
Classes.Globe.prototype = Classes._proto
Classes.Umbrella.prototype = Classes._proto
$(document).ready(function(){
var globe, umb, igloo, house;
globe = new Classes.Globe();
umb = Classes.Umbrella;
igloo = new Classes.Igloo("Ice");
house = new Classes.House();
var objects = [globe, umb, igloo, house]
for(var i = 0, len = objects.length; i < len; i++){
var me = objects[i];
if("whatAreYou" in me){
console.log(me.whatAreYou())
}else{
console.warn("unavailable")
}
}
})
and make this.name into _name (the "private" property), it doesn't work, and instead outputs:
My House
unavailable
My House
My House
Would someone be kind enough to explain this one? Obviously _name is being overwritted upon each iteration and not reading the object's property of which it's attached.
This all seems a little too verbose needing this and kinda weird IMO.
Thanks :)
You declare a global variable. It is available from anywhere in your code after declaration of this. Wherever you request to _name(more closely window._name) you will receive every time a global. In your case was replaced _name in each function. Last function is House and there has been set to "My House"
Declaration of "private" (local) variables must be with var statement.
Check this out:
var foo = function( a ) {
_bar = a;
this.showBar = function() {
console.log( _bar );
}
};
var a = new foo(4); // _bar ( ie window._bar) is set to 4
a.showBar(); //4
var b = new foo(1); // _bar is set to 1
a.showBar(); //1
b.showBar(); //1
_bar = 5; // window._bar = 5;
a.showBar();// 5
Should be:
var foo = function( a ) {
var _bar = a;
// _bar is now visibled only from both that function
// and functions that will create or delegate from this function,
this.showBar = function() {
console.log( _bar );
};
this.setBar = function( val ) {
_bar = val;
};
this.delegateShowBar = function() {
return function( ) {
console.log( _bar );
}
}
};
foo.prototype.whatever = function( ){
//Remember - here don't have access to _bar
};
var a = new foo(4);
a.showBar(); //4
_bar // ReferenceError: _bar is not defined :)
var b = new foo(1);
a.showBar(); //4
b.showBar(); //1
delegatedShowBar = a.delegateShowBar();
a.setBar(6);
a.showBar();//6
delegatedShowBar(); // 6
If you remove the key word "this", then the _name is in the "Globe" scope.
Looking at your code.
var globe, umb, igloo, house;
globe = new Classes.Globe();
umb = Classes.Umbrella;
igloo = new Classes.Igloo("Ice");
house = new Classes.House();
At last the house will override the "_name" value in globe scope with the name of "My House".

Categories