Variables Pointing To The Same Function - javascript

I have created a new variable, carBasket and foodBasket, and set them equal to the basketModule() function. They however are pointed to the same function when I want each of these two variables pointed to their own function. I am wondering what should I be doing to achieve this?
var basketModule = (function() {
var basket = [];
return {
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
}
};
}());
carBasket = basketModule;
carBasket.addItem('Audi');
foodBasket = basketModule;
foodBasket.addItem('Ham');
foodBasket.getItemCount(); //outputs 2 instead of 1

You must call a function for each object in order to generate different variables for each one, e.g:
var basketModule = function() {
var basket = [];
return {
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
}
};
};
var carBasket = basketModule(),
foodBasket = basketModule();
carBasket.addItem('Audi');
foodBasket.addItem('Ham');
foodBasket.getItemCount(); // 1
However, in order to reuse the methods for all instances, better use a constructor:
var BasketModule = function() {
this.basket = [];
};
BasketModule.prototype.addItem = function(values) {
this.basket.push(values);
};
BasketModule.prototype.getItemCount = function() {
return this.basket.length;
};
var carBasket = new BasketModule(),
foodBasket = new BasketModule();
carBasket.addItem('Audi');
foodBasket.addItem('Ham');
foodBasket.getItemCount(); // 1

You should consider trying this pattern instead:
var BasketModule = function() {
var basket = [];
return {
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
}
};
};
carBasket = new BasketModule();
carBasket.addItem('Audi');
foodBasket = new BasketModule();
foodBasket.addItem('Ham');
jsfiddle: https://jsfiddle.net/nvsbjset/
This will create separate objects for each basket

Related

Can't have access to a variable using call in Javascript

I'm studying Javascript and learning how to use call. I created this script and I don't know why I can't have access to this variable Time.
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {});
var myNewObj = new MyObject.Runner(1000); myNewObj.newTest('1', function() {
console.log(this.time) //output: undefined
});
So how can I get time value inside newTest function?
Issue is in newTest function
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
Here this is pointing to test and not Runner. You will have to save context in a variable and then set it in call.
Runner.prototype.newTest = function(index, execute) {
var self = this;
var test = function() {
return execute.call(self);
}
myFunctionArray.push(test);
}
.call + self
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
var self = this;
var test = function() {
return execute.call(self);
}
myFunctionArray.push(test);
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {}));
var myNewObj = new MyObject.Runner(1000);
myNewObj.newTest('1', function() {
console.log(this, this.time) //output: undefined
});
myNewObj.execute()
.bind
As commented, you can even use .bind
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
myFunctionArray.push(execute.bind(this));
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {}));
var myNewObj = new MyObject.Runner(1000);
myNewObj.newTest('1', function() {
console.log(this, this.time) //output: undefined
});
myNewObj.execute()
When you declare your Runner function, you've actually declared a function that takes no arguments that then itself declares a function called Runner that takes one argument.
Actually In this code snippet :
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
this will reference to test variable (as per constructor invocation pattern)
So, to pass right variable cache the value of this in another variable and then pass that to function.

A Javascript function which creates an object which calls the function itself

I am trying to make an angular service that returns a new object.
That's fine and good and works. new MakeRoll() creates an instance. But self.add, near the end also calls new MakeRoll() and that doesn't create an instance when I call add like I think it should.
I'm probably doing this all wrong but I haven't been able to figure it out.
var services = angular.module('services', []);
services.factory('Roll', [function() {
var MakeRoll = function () {
var self = {};
self.rolls = [];
self.add = function(number, sizeOfDice, add) {
var newRoll = {};
newRoll.number = number || 1;
newRoll.sizeOfDice = sizeOfDice || 6;
newRoll.add = add || 0;
newRoll.rollDice = function() {
var result = 0;
var results=[];
for (var i = 0; i < newRoll.number; i++) {
var roll = Math.floor(Math.random() * newRoll.sizeOfDice) + 1;
result += roll;
results.push(roll);
}
newRoll.results = results;
newRoll.result = result;
newRoll.Roll = new MakeRoll();
};
self.rolls.push(newRoll);
return self;
};
self.remove = function(index) {
self.rolls.splice(index, 1);
};
self.get = function(index) {
return self.rolls[index];
};
return self;
};
return new MakeRoll();
}
]);
angular service is designed to be singleton to accomplish some business logic, so don't mix up plain model with angular service. if you want to have more objects, just create a constructor and link it in service to be operated on.
function MakeRoll() {
...
}
angular.module('service', []).factory('Roll', function () {
var rolls = [];
return {
add: add,
remove: remove,
get: get
}
function add() {
// var o = new MakrRoll();
// rolls.push(o);
}
function remove(o) {
// remove o from rolls
}
function get(o) {
// get o from rolls
}
});

Confusion on how to use functions in javascript

This is what I am trying to implement.
var globalVar = [];
var tomakeJson = JSON.Stringify(globalVar);
window.load = function grpwrk() {
hdWork: function() {
// return somefatherwork;
};
asstWork: function() {
// return somemotherWork;
};
};
To call a function
globalVar.push(familyWork(hdWork()));
globalVar.push(familyWork(asstWork()));
Then tomakeJson is send to backend server and gets stored in NoSQL.
Is this implementation right? Is there any other way to use this type of function?
This is some idea of code.
function StackHandler(){
var stack = new Array();
this.push = function(obj){
return stack.push(obj);
};
this.pop = function(){
return stack.pop();
};
this.getJSON = function(){
return JSON.stringify(stack);
};
};
var familyWork = {
fatherWork : function(){
// return somefatherwork;
},
motherWork : function(){
// return somemotherWork;
},
broWork : function(){
// return somebroWork;
},
sisterWork : function(){
// return somesisterWork;
}
};
var globalVar = new StackHandler();
globalVar.push(familyWork.fatherWork());
globalVar.push(familyWork.motherWork());
globalVar.push(familyWork.broWork());
globalVar.push(familyWork.sisterWork());
globalVar.getJSON(); // return JSON

how to call function using name such as "function someName(){}"?

I have a name of a private function in JavaScript as a string, how do I call that function?
var test = function () {
this.callFunction = function(index) {
return this["func" + index]();
}
function func1() { }
function func2() { }
...
function funcN() { }
}
var obj = new test();
obj.callFunction(1);
func1 and friends are local variables, not members of the object. You can't call them like that (at least not in any sane way).
Define them with function expressions (instead of function declarations) and store them in an array.
var test = function () {
this.callFunction = function(index) {
return funcs[index]();
}
var funcs = [
function () {},
function () {},
function () {}
];
}
var obj = new test();
obj.callFunction(0);
As your code stands, the functions are not present as properties of the instance. What you need to do is create them as properties of the context.
var test = function () {
this.callFunction = function(index) {
return this["func" + index];
}
this.func1 = function() { }
this.func2 = function() { }
...
}
var obj = new test();
obj.callFunction(1)();
you can use eval
var test = function () {
this.callFunction = function(index) {
return eval("func" + index + '()');
}
function func1() {
return 1;
}
function func2() {
return 2;
}
function funcN() { }
};
var obj = new test();
obj.callFunction(2);
eval is evil
You can use a private array of functions:
var test = function() {
var func = [
function() { return "one" },
function() { return "two"; }
]
this.callFunction = function(index) {
return func[index]();
}
}
var obj = new test();
var ret = obj.callFunction(1);
console.log(ret);​
​
http://jsfiddle.net/V8FaJ/

encapsulation in javascript module pattern

I was reading this link http://addyosmani.com/largescalejavascript/#modpattern
And saw the following example.
var basketModule = (function() {
var basket = []; //private
return { //exposed to public
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
},
getTotal: function(){
var q = this.getItemCount(),p=0;
while(q--){
p+= basket[q].price;
}
return p;
}
}
}());
basketModule.addItem({item:'bread',price:0.5});
basketModule.addItem({item:'butter',price:0.3});
console.log(basketModule.getItemCount());
console.log(basketModule.getTotal());
It stats that "The module pattern is a popular design that pattern that encapsulates 'privacy', state and organization using closures" How is this different from writing it like the below? Can't privacy be simply enforced with function scope?
var basketModule = function() {
var basket = []; //private
this.addItem = function(values) {
basket.push(values);
}
this.getItemCount = function() {
return basket.length;
}
this.getTotal = function(){
var q = this.getItemCount(),p=0;
while(q--){
p+= basket[q].price;
}
return p;
}
}
var basket = new basketModule();
basket.addItem({item:'bread',price:0.5});
basket.addItem({item:'butter',price:0.3});
In the first variant you create an object without the possibility to create new instances of it (it is an immediately instantiated function). The second example is a full contructor function, allowing for several instances. The encapsulation is the same in both examples, the basket Array is 'private' in both.
Just for fun: best of both worlds could be:
var basketModule = (function() {
function Basket(){
var basket = []; //private
this.addItem = function(values) {
basket.push(values);
}
this.getItemCount = function() {
return basket.length;
}
this.getTotal = function(){
var q = this.getItemCount(),p=0;
while(q--){
p+= basket[q].price;
}
return p;
}
}
return {
basket: function(){return new Basket;}
}
}());
//usage
var basket1 = basketModule.basket(),
basket2 = basketModule.basket(),

Categories

Resources