Hi can someone tell me why I can't instantiate the following class/object?
function Arbitrage(odds1, odds2, investment)
{
this.investment = investment;
this.odds1 = odds1;
this.odds2 = odds2;
this.arbPercent = function() {
return 1.0/this.odds1 + 1.0/this.odds2;
};
this.profit = function() {
return this.investment / this.arbPercent() - this.investment;
};
this.individualBets = function() {
return {
odds1bet : this.investment/this.odds1/this.arbPercent(),
odds2bet : this.investment/this.odds2/this.arbPercent()
};
};
};
module.exports = Arbitrage;
I'm calling it like this:
var utility = require('../businesslogic/utility');
...
router.post('/calculate', function(req, res)
{
var arbit = new utility.Arbitrage(req.body.odds1, req.body.odds2, req.body.investment);
res.json({
arbPercentage : arbit.arbPercent(),
profit : arbit.Profit(),
indvBets : arbit.individualBets()
});
});
The first line, var arbit = new utility.Arbitrage(...) is throwing the error.
It says TypeError: undefined is not a function
I've checked that utility isn't null or anything like that. Also all the constructor arguments are ok.
I'm not very familiar with javascript, any help would be appreciated. Thanks.
You're exporting your Arbitrage class directly, so after you're requiring it
var utility = require('../businesslogic/utility');
utility is actually your Arbitrage class, meaning that typeof utility === 'function'.
I can see two ways of fixing it.
1. Change the way you're requiring your Arbitrage class:
var Arbitrage = require('../businesslogic/utility');
// ...
var arbit = new Arbitrage(...);
2. Or change the way you're exporting it:
exports.Arbitrage = Arbitrage;
it's because of the way you exported it
you should use :
module.exports.Arbitrage = Arbitrage;
And then you can instanciate like this :
var Arbitrage = require('../businesslogic/utility');
var varbitrage = new Arbitrage();
Related
I have 2 js functions:
function onRegionMouseOver()
{
}
function onRegionMouseOut()
{
}
Is it possible to call these js functions dynamically doing something like this?:
var type = 'Out'
//the following line would exec onRegionMouseOut() above:
call(onRegionMouse[type]())
You can use this:
var onRegionMouseHandlers = {
out: function () {},
in: function () {}
}
// and using like this
var whatToUse = 'in';
// use
onRegionMouseHandlers[whatToUse]()
Also, you can remove your which choose what function have to be called. You can just add two handlers to two different events.
You can define the functions as properties of an object, use bracket notation to call the function.
const methods = {
onRegionMouseOver() {console.log("Over")},
onRegionMouseOut() {console.log("Out")}
}
let fn = "onRegionMouse";
let type = "Out";
methods[`${fn}${type}`]();
type = "Over";
methods[`${fn}${type}`]();
without template literal or let
var methods = {
onRegionMouseOver: function onRegionMouseOver() {console.log("Over")},
onRegionMouseOut: function onRegionMouseOu() {console.log("Out")}
}
var fn = "onRegionMouse";
var type = "Out";
methods[fn + type]();
type = "Over";
methods[fn + type]();
You can do something like that, provided you declare an object that contains the functions.
var onRegionMouse = {
Out: onRegionMouseOut,
Over: onRegionMouseOver
};
Now you can just do
var type = 'Out';
onRegionMouse[type]();
what about:
var myFunctions = {
out: function onMouseOut()...,
enter: function onMouseEnter()...
}
You can call it now with myFunctions[ "out" ] ()
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);
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
Okay so we have a project ongoing, and it is to be passed today. But I have a problem.
This is the sample code:
output.js
var MapPrintDialog = Class.create();
MapPrintDialog.prototype = {
// 他の画面からテンプレート情報を更新するために呼ばれる。
comboReload : function() {
var val = tempComb.getValue();
tempComb.store.load({
callback: function(result, o) {
if (this.store.data.keys.indexOf(val) == -1) {
this.setValue(this.store.data.keys[0]);
this.fireEvent("select", this);
}
}.createDelegate(tempComb)
});
},
initialize : function(){
this.define();
},
define : function(){
var DrawPrintAreaFrame = function(mode, noUpdateStatusBarText){
var cs = getCurrentSetting();
if (mode == "init" || mode == "edit"){
PrintController.DrawMapPrintArea(cs.center.x, cs.center.y, cs.scale, cs.result.PrintMaps[0].Width, cs.result.PrintMaps[0].Height, cs.result.PageRowCount, cs.result.PageColumnCount, mode);
}
else if (mode == "delete"){
PrintFrameManager.ClearPrintFrame();
}
if (noUpdateStatusBarText) {
gisapp.noUpdateStatusBarText = true;
}
gisapp.refreshMap();
}
}
Now my problem is, how will I call "DrawPrintAreaFrame" from another js file?
I tried:
MapPrintDialog.prototype.define().DrawPrintAreaFrame("edit");
MapPrintDialog.prototype.define.DrawPrintAreaFrame("edit");
MapPrintDialog.define().DrawPrintAreaFrame("edit");
MapPrintDialog.define.DrawPrintAreaFrame("edit");
MapPrintDialog.DrawPrintAreaFrame("edit");
DrawPrintAreaFrame("edit");
but it gives me an error lol. How will I fix this? Please don't be too harsh, I just started learning javascript but they gave me an advanced project which isn't really "beginner" friendly XD
EDIT ----------------------
Okay now i tried to modify it like this:
var MapPrintDialog = Class.create();
MapPrintDialog.prototype = {
// 他の画面からテンプレート情報を更新するために呼ばれる。
comboReload : function() {
var val = tempComb.getValue();
tempComb.store.load({
callback: function(result, o) {
if (this.store.data.keys.indexOf(val) == -1) {
this.setValue(this.store.data.keys[0]);
this.fireEvent("select", this);
}
}.createDelegate(tempComb)
});
},
initialize : function(){
this.DrawPrintAreaFrame("edit");
}
}
function DrawPrintAreaFrame(mode, noUpdateStatusBarText){
var cs = gisapp.getCurrentView();
if (mode == "init" || mode == "edit"){
PrintController.DrawMapPrintArea(cs.center.x, cs.center.y, cs.scale, cs.result.PrintMaps[0].Width, cs.result.PrintMaps[0].Height, cs.result.PageRowCount, cs.result.PageColumnCount, mode);
}
else if (mode == "delete"){
PrintFrameManager.ClearPrintFrame();
}
if (noUpdateStatusBarText) {
gisapp.noUpdateStatusBarText = true;
}
gisapp.refreshMap();
}
But it gives me: Javascript runtime error: Object doesn't support property or method 'DrawPrintAreaFrame'
You have 2 different way:
1- you have to first change it like this:
define : function(){
var DrawPrintAreaFrame = function(mode, noUpdateStatusBarText){
//You function code
}
this.getDrawPrintAreaFrame = function(){
return DrawPrintAreaFrame;
}
}
then create your object using your class:
var obj = new MapPrintDialog();
obj.define();
obj.getDrawPrintAreaFrame().call(obj, "edit");
2- remove the define method and add your function to prototype:
MapPrintDialog.prototype.DrawPrintAreaFrame = function(){
//your function code
}
create your object and simply call your method like this:
var obj = new MapPrintDialog();
obj.DrawPrintAreaFrame("edit");
It's funny, because I said you have 2 ways, and the third one just came up:
3- as far as you use Prototype framework you can use MapPrintDialog.addMethods, which is there to be used to add new instance methods to your class, remove your define and DrawPrintAreaFrame functions and add this:
MapPrintDialog.addMethods({
DrawPrintAreaFrame: function DrawPrintAreaFrame(){
//your code
}
});
or even without removing your method you can use it like:
define : function(){
var DrawPrintAreaFrame = function(mode, noUpdateStatusBarText){
//You function code
}
MapPrintDialog.addMethods({ DrawPrintAreaFrame: DrawPrintAreaFrame });
}
and create your instance and call the method:
var obj = new MapPrintDialog();
obj.DrawPrintAreaFrame("edit");
4- try this if you need your function like a sort of static method, without needing to create a instance:
MapPrintDialog.DrawPrintAreaFrame = function(){
//You function code
}
and call it like this
MapPrintDialog.DrawPrintAreaFrame("edit");
and if you want to define it in runtime, add the whole definition to your define method like this:
define : function(){
MapPrintDialog.DrawPrintAreaFrame = function(){
//You function code
}
}
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>