How to pass the parameter to autonomous function and get the values? - javascript

On load of the document, I am initiating a function calling itself. And later from the returned function, i am trying to get the output. but i am not getting. the way what i do this wrong here.
any one correct me and teach the correct way to use the self initiated functions?
here is my try :
var BankAccount = (function () {
function BankAccount() {
this.balance = 0;
}
BankAccount.prototype.deposit = function(credit) {
this.balance += credit; return this.balance;
};
return BankAccount;
})();
var myDeposit = BankAccount.deposit(50); //throws error as ankAccount.deposit is not a function
Live

You need to return instance of BankAccount:
return new BankAccount();

You need to invoke your constructor before you can call .deposit
var account = new BankAccount();
var balance = account.deposit(50);
console.log(balance); // 50
This would allow you to manage multiple accounts where each account has its own balance.
var a = new BankAccount();
a.deposit(50); // 50
var b = new BankAccount();
b.deposit(20); // 20
console.log(a.balance); // 50
console.log(b.balance); // 20

You've written a constructor function, but you haven't called it as one.
var myBankAccount = new BankAccount();
var myDeposit = myBankAccount.deposit(50);

Related

Using function of an object after grabbing it from array

When I try to grab the object from the array, the type is undefined. Therefore I cannot use a method from the undefined object as it doesn't exist. I am relatively new to JavaScript and I have come straight from Java so the way of retrieving objects is kind of new to me. This is what I currently have.
var fleetAmount = 0;
var fleets = [];
function Fleet(number) {
this.number = number;
this.activities = [];
this.addActivity = function (activity) {
this.activities.push(activity);
};
fleets.push(this);
}
var getFleet = function(fleetNumber) {
return fleets[fleetAmount - fleetNumber];
}
This is where I try to grab the object and preform the function
const Fl = require(‘fleet.js’);
const fleet = Fl.getFleet(fleetNumber);
fleet.addActivity(activity);
I am also working in Node.js, which is how I am using the require method.
In combination with the answer from #audzzy I changed the getFleet() function so that it would be more efficient. I tested it out and it worked. This is what I used
function getFleet(fleetNumber) {
let result = fleets.filter(function (e) {
return e.number = fleetNumber;
})
return result[0];
}
Thanks for the help! I appreciate it.
you want to create a new fleet object and add it, not "this"..
adding "this" would cause a circular reference, where
this.fleets[i] = this (and all fleets would have the same value)
when calling get fleet, I would check that a fleet was returned from get fleet
in case amount is less than the number you send to getFleet (where according to what you posted: 1 returns the last, 2 returns second to last etc..)..
I hope this explanation makes sense.. anyways, this should work..
var fleets = [];
doStuff();
function doStuff(){
addFleet(1);
addFleet(2);
addFleet(7);
addFleet(3);
// should return null
let fleet1 = getFleetByNumber(5);
// should return the fleet with number 7, and not change the fleet with number 1
let fleet2 = getFleetByNumber(7);
if(fleet2){
fleet2.addActivity("activity");
}
console.log(`fleets: ${JSON.stringify(fleets)} \nfleet1: ${JSON.stringify(fleet1)} \nfleet2: ${JSON.stringify(fleet2)}`);
}
function addFleet(number) {
let fleet = { number: number,
activities: [] };
fleet.addActivity = function (activity) {
this.activities.push(activity);
};
fleets.push(fleet);
}
function getFleetByNumber(fleetNumber) {
return fleets.find(function (e) {
return e.number == fleetNumber;
});
}
function getFleet(fleetNumber) {
let result = null;
if(fleets.length - fleetNumber >= 0){
result = fleets[fleets.length - fleetNumber];
}
return result;
}

How do I find the right Friends?

I am not sure how to find the right one or to search me out of it
// Assignment 8: Fix the code
// Assignment 8: Fix the code
var Friends = (function() {
var i = 0;
function Friends() {
var ival = setInterval(function() {
console.log(this.friends[i]);
i++;
if(i === this.friends.length) {
clearInterval(ival);
}
}, 1000);
}
Friends.prototype.friends = ['Mikkel', 'Jens', 'Filip'];
return Friends;
})();
var f = new Friends();
var f2 = new Friends();
/* it should log:
Mikkel
Mikkel
Jens
Jens
Filip
Fili
/* it should log:
Mikkel
Mikkel
Jens
Jens
Filip
Fili
There are two issues with this code snippet,
Uncaught TypeError: Cannot read property '0' of undefined
context of variable "i" is same for both instance of friends.
First issue was due to the context of the variable this inside setInterval function. To access the friends inside setInterval keep the reference of this into a variable outside setInterval and access that variable inside the function. In the below code I have assigned this to a variable me, and accessed friends list using me.
Second issue is with the indexing of item using i. As we have defined it out side the function Friends, indexing will same in both initialisation. Which will result in following result:
Mikkel
Jens
Filip
undefined
undefined
undefined ....
So to make sure when ever we call new Friends() the it should start from the beginning of the friends list move the initialisation of var i = 0 inside Friends function.
Below is the updated code which will give the exact result.
var Friends = (function() {
function Friends() {
var i = 0; // Solution for second issue
var me = this; // Solution for first issue
var ival = setInterval(function() {
console.log(me.friends[i]);
i++;
if(i === me.friends.length) {
clearInterval(ival);
}
}, 1000);
}
Friends.prototype.friends = ['Mikkel', 'Jens', 'Filip'];
return Friends;
})();
var f = new Friends();
var f2 = new Friends();

How do we return function using module.exports in nodeJS?

How do we return function using module.exports in nodeJS?
file_1 book.js
module.exports = function() {
var points = 0;
return {
rate: function(value) {
points = value;
},
get: function() {
return points;
}
}
}
book.js is root file. We create two different instances but can not get the methods of root to script.js file.
file_2 main.js
var bA = require('./book.js');
var bB = require('./book.js');
bB.rate(10);
bB.get();
Output => can not find rate and get method.
Because the function returns an object with references to the rate and get functions, you need to execute it with a () on require like so:
var book = require('./book.js')();
book.rate(10);
book.get();
You're returning a function which returns an object.
Call the function and get the object
/*file_2 main.js*/
var bA = require('./book.js')();
var bB = require('./book.js')();
bB.rate(10);
bB.get();
Just in case if someone's facing same problem as me
I had something issue with my code. Lately realised I was making some API call and so return returned an object before fetching the value from API endpoint
I added async in front of function call and it worked!
var util=require('./app/Utils')
const url=await util.getInfo();
You can also provide a name to your anonymous export function as
module.exports.myfun = function() {
var points = 0;
return {
rate: function(value) {
points = value;
},
get: function() {
return points;
}
} }
Then use the function in another file as
var inc = require('./comp.js');
var mod = inc.myfun();
mod.rate(10);
console.log(mod.get());
In this way you don't need to have '()' at the time of required, though that option can also be used

Cloning anonymous function

Hello I've used this patter to get a static variable
var uniqueID = (function() {
var id = 0; // This is the private persistent value
// The outer function returns a nested function that has access
// to the persistent value. It is this nested function we're storing
// in the variable uniqueID above.
return function() { return id++; }; // Return and increment
})(); // Invoke the outer function after defining it.
Now I'm trying to clone this function, but backup and the original still return sequential values. How can i "freeze" the status of the function when copy it?
Thanks
OK, something like this extremely convoluted contraption should work (fiddle, http://jsfiddle.net/dPLj6/):
var uniqueIdFunction = function(initialValue) {
var id = initialValue || 0;
var result = function() { return id++; };
result.clone = function(){ return uniqueIdFunction(id); }
return result;
};
var uniqueId1 = uniqueIdFunction();
Use the clone method to get a clone. The original will keep it's own internal id value. The clone will take its initial internal id from the clone source.
Here is a function that generates unique id generators:
var createGenerator = function(id) {
var id = id || 0;
return function() { return id++; };
}
var g1 = createGenerator();
var g2 = createGenerator();
console.log(g1(), g1(), g1());
console.log(g2(), g2());
console.log(g1());
console.log(g2());
// OP's cloning scenario
var freezeId = g1();
var clone = createGeenrator(freezeId);
console.log(g1(),g1());
console.log(clone());
#pax162's answer is more in line with what the OP wants to do. I just decided to post the more normal way of doing it.

scratching my head over "this" statement in javascript. anyone help please

Ok after a day I managed to narrow down the problem to 2 lines of code. Maybe I am trying to use the this statement incorrectly.
function scheduleItemView(myId){
this.update = function(show){
document.getElementById(this.id+'-title').innerHTML = show.title +": "+ show.startDate;
document.getElementById(this.id+'-title-overlay').innerHTML = show.title +": "+ show.startDate;
document.getElementById(this.id+'-description').innerHTML = truncate(show.description,190);
document.getElementById(this.id+'-time-start').innerHTML = show.startTime;
document.getElementById(this.id+'-time-end').innerHTML = show.endTime;
};
this.id=myId;
return true;
}
function nowNextView(){
this.now = new scheduleItemView('now');
this.next = new scheduleItemView('next');
this.update = function(type,args){
var myshow=args[0];
// problem is below. I have to use the global name to access the update method.
myNowNextView.now.update(myshow.now);
myNowNextView.next.update(myshow.next);
// whereas what I want to do is reference them using the "this" command like below.
// this.now.update(myshow.now);
// this.next.update(myshow.next);
// the above doesnt work. The update method in scheduleItemView is not seen unless referenced globally
// BUT even more infuriating, this.now.id does return "now" so it can access the object, just not the method
// any ideas?
};
}
object is then instantiated with
var myNowNextView = new nowNextView();
and then I run the method:
myNowNextView.update(stuff);
I tried to describe the problem within the body of the program. No error in the code was thrown, and I had to do a try/catch before it grudgingly told me that it couldn't find the method.
Is the design flawed somehow? can I not do this?
Many thanks in advance,
Steve
function scheduleItemView(myId){
this.update = function(show){
document.getElementById(this.id+'-title').innerHTML = show.title +": "+ show.startDate;
document.getElementById(this.id+'-title-overlay').innerHTML = show.title +": "+ show.startDate;
document.getElementById(this.id+'-description').innerHTML = truncate(show.description,190);
document.getElementById(this.id+'-time-start').innerHTML = show.startTime;
document.getElementById(this.id+'-time-end').innerHTML = show.endTime;
};
this.id=myId;
}
function nowNextView(){
var myshow=args[0];
var scope = this;
this.now = new scheduleItemView('now');
this.next = new scheduleItemView('next');
this.update = function(type,args){
scope.now.update(myshow.now);
scope.next.update(myshow.next);
};
}
I think you could really benefit from studying closures a bit in javascript. It seems like you are trying to apply a traditional OO approach to js objects, and that won't give you the results you are expecting.
I would recommend reading over this post for an easy way to use closures:
http://howtonode.org/why-use-closure
Something like this:
<html>
<head>
<script type="text/javascript">
function createScheduleItemView(myId){
var _show = false
return {
setShow : function setShow(show) {
_show = show
},
update : function update(){
document.getElementById( myId +'-title').innerHTML = _show.title;
}
}
}
function createNowNextView(){
var _now = createScheduleItemView('now');
var _next = createScheduleItemView('next');
return {
publicVar : "Example",
update : function update(args) {
var myshow=args[0];
_now.setShow(myshow.now)
_now.update();
_next.setShow(myshow.next)
_next.update();
}
};
}
function runIt() {
nowNextView = createNowNextView()
args = []
showArgs = {
now : {title : "Beauty and the Beast"},
next : {title: "I did it myyyyyy way"}
}
args.push(showArgs)
nowNextView.update(args)
//Private variables can not be accessed
//console.log(nowNextView._now)
//undefined
//
//But anything you return in the object is public
//console.log(nowNextView.publicVar)
//Example
}
</script>
</head>
<body onload="runIt()">
<h3>Now Showing:</h3>
<p id="now-title"></p>
<h3>Up Next:</h3>
<p id="next-title"></p>
</body>
</html>

Categories

Resources