JavaScript object returning null value [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
What is wrong with this code?
function makeGamePlayer(int) {
var bal = 0;
var obj = {
fun1: function () {
bal += int;
},
fun2: function () {
return bal;
}
};
return obj;
}
console.log(makeGamePlayer(100)); //obj
console.log(makeGamePlayer(100).fun2()); //returning 0 but expecting the 100
I tried running the above code but I'm not getting the correct results. I need some help.
Thanks in advance.

The ONLY way to make the second console.log output 100 without changing the makeGamePlayer code at all is as follows
function makeGamePlayer(int) {
var bal = 0;
var obj = {
fun1: function () {
bal += int;
},
fun2: function () {
return bal;
}
};
return obj;
}
// commented, as it's irrelevant
//console.log(makeGamePlayer(100)); //obj
var x = makeGamePlayer(100); // x is a **different obj and bal by the way**
x.fun1();
console.log(x.fun2());
// to illustrate that each time you call `makeGamePlayer` you get a new obj and a new bal
var y = makeGamePlayer(1000);
y.fun1();
// note, this is STILL 100
console.log(x.fun2());
// this outputs 1000
console.log(y.fun2());
// output
// 100
// 100
// 1000

You are incrementing int in fun1 function, but you haven't called in anywhere. You have called fun2 function which is returning the bal as it is.

Related

Why am I getting ':' expected"? I'm trying to define a few functions to run some unit tests on for a benchmark [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm trying to get these functions defined to run some synchronous and asynchronous test cases on them with Mocha and Chai in JS, what am I doing wrong? Why is my editor marking certain lines?
module.exports = {
function myFunctiona () {
}
function myFunctionb () {
for (let i = 0; i < 10000; i++) {
new Date();
}
}
function myFunctionc(done) {
setTimeout(done, 0);
}
function myFunctiond (done) {
setTimeout(done, Math.round(Math.random() * 10));
}
}
This is a syntax error because you're defining an object with properties, but you don't have property keys. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_colon_after_property_id for more information.
Typically, you'd define an object like the following
(note the commas after each property too):
var object = {
property1: 'thing',
property2: function() {
return 'thing2';
}
}
so to change your functions to properties, set the property key as the function name, and then assign a function to it like:
module.exports = {
myFunctiona: function () {
//nothing
},
myFunctionb: function () {
for (let i = 0; i < 10000; i++) {
new Date();
}
},
myFunctionc: function (done) {
setTimeout(done, 0);
},
myFunctiond: function (done) {
setTimeout(done, Math.round(Math.random() * 10));
}
};

Javascript cannot find a function that was converted from a string [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to convert a string into a function without using eval(), however whenever I pass the function name into the window object and check its type. Javascript does not seem to recognize it as a function. I always get this custom error message I've defined in the else statement: "Could not find function: 1->validateLogin".
My dom_ready prototype:
dom_ready: function (inputFunc) {
document.addEventListener("DOMContentLoaded", function () {
try {
inputFunc();
} catch (e) {
DN.errors.push(e.message);
}
});
},
function show_pass() {
...
}
function validateLogin(k) {
...
}
DN.DOM.dom_ready(function () {
var event_ids = [
["#login-form-dialog", "validateLogin", "submit", 1]
["#loginnotes", "validateLogin", "click", 1],
["#loginnotes2", "validateLogin", "click", 2],
["#show-pass", "show_pass", "click", ""],
]
for (var i = 0; i < event_ids.length - 1; i++) {
var fN = window[event_ids[i][1]];
if (typeof fN === 'function') {
$(event_ids[i][0]).on(event_ids[i][2], function () {
fN(event_ids[i][3]);
})
} else {
console.log("Could not find function: " + i + "->" + event_ids[i][1]);
}
}
});
The particular syntax error causing your problems was addressed in other answers. To find such syntax errors, look at the console for errors. Or, run your code through a linter. Otherwise, you will have to post to SO every time you forget a comma, which does not seem to be a very scalable approach.
More basically, do not pass around function references using strings giving their names, which you need to then look up on the window object. Instead, just pass the function reference itself (validateLogin). Unlike some other languages, in JS functions are first-class citizens which can be referred to and passed around as themselves. Your code would look like this:
DN.DOM.dom_ready(function () {
var event_ids = [
["#login-form-dialog", validateLogin, "submit", 1]
^^^^^^^^^^^^^
...
for (var i = 0; i < event_ids.length - 1; i++) {
var fN = event_ids[i][1];
Of course, you will have to make sure that validateLogin is visible at the time this ready function is executed.
However, you have a more basic problem which will prevent your code from running properly, in the following lines:
$(event_ids[i][0]).on(event_ids[i][2], function () {
fN(event_ids[i][3]);
})
Here, the anonymous function is a closure over the variable i, and at the time it is executed (when the event occurs), i will already be at its maximum value of 3. There are many questions and answers on this topic here on SO, but the easiest solution is to use for (let i, if you are working in an environment that supports let. Otherwise, see questions like this one.
You are missing a comma after the first item in event_ids:
var event_ids = [
["#login-form-dialog", "validateLogin", "submit", 1], // <-- missing comma
["#loginnotes", "validateLogin", "click", 1],
["#loginnotes2", "validateLogin", "click", 2],
["#show-pass", "show_pass", "click", ""],
]; // <-- also it is better practice to have semi-colon here

Add function to Object with an element selector [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have an Object
function Object(name, button) {
this.name = name;
this.button = button;
var alert = function () {
alert("x");
};
}
var ExampleOne = new Object('Example One', $('.exampleButton'));
How can I make the function inside the object fire on an event of Object[button]...
Using -
ExampleOne.button.click(function () {
ExampleOne.alert();
});
Doesn't work.
var alert = function is a local function and cannot be accessed outside that object. If you want it to be accessible with new instances, declare it with this:
function Object(name, button) {
this.name = name;
this.button = button;
this.alert = function () {
alert("x");
};
}
Fiddle: http://jsfiddle.net/qow3qu0m/2/
It's working for me. Check your code again. Maybe you forgot to include jQuery?
ExampleOne.button.click(function(e) {
alert('success!');
});
http://codepen.io/anon/pen/yyGpLz

How do I increment the value of a variable by 1 every 3 seconds? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
$(document).ready(function() {
var addTime = function() {
var time = 1;
setInterval((function() {
time = time + 1;
}), 3000);
console.log(time);
};
addTime();
});
Right now, it only outputs 2. What Am I doing wrong?
It is being incremented. But it's printed only once.
try this
$(document).ready(function() {
var addTime = function() {
var time = 1;
setInterval((function() {
time = time + 1;
console.log(time);
}), 3000);
};
addTime();
});
Below javascript function would help you.
window.setInterval("javascript function",milliseconds);
And here is the sample code
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
// code you want to execute
}
You can also refer the Jquery Timer..below is the link
http://jchavannes.com/jquery-timer/demo
Here are the multiple options available
var timer = $.timer(function() {
alert('This message was sent by a timer.');
});
timer.set({ time : 5000, autostart : true });
timer.set(options);
timer.play(reset); // Boolean. Defaults to false.
timer.pause();
timer.stop(); // Pause and resets
timer.toggle(reset); // Boolean. Defaults to false.
timer.once(time); // Number. Defaults to 0.
timer.isActive // Returns true if timer is running
timer.remaining // Remaining time when paused

Add parameter to function dynamically [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
// set Process
i18n.setProcess(function() {diFunctions.getI18n('http://localhost/service/i18n/page?lang=eng&group=staff') });
// Setter and getter
this.setProcess = function( opProcess ) { //here param opProcess is function with parameters see i18n.setProcess() line of code
if( opProcess == undefined)
throw "Process is undefined";
if( $.isFunction(opProcess) == false )
throw "Process is not a function"
process = opProcess;
};
this.getProcess = function() {
return process;
};
See how i18n.setProcess passes a function with param as a parameter to setProcess.
Now i what i want in SetProcess is function() {diFunctions.getI18n('http://localhost/service/i18n/page?lang=eng&group=staff',**id**) // id is added dynamically to the function itself which was passed as parameter to setProcess
Problem - I want to add id dynamically(defined in my class variable always accesible by id) on set process with addition to functions parameter(Url,etc,etc,id). Functions parameters can grow but the id should be added last as a parameter?
Tried quite a few solutions but didnot work out? Check here
This is what the arguments object is for..
function foo() {
var lastArg = arguments.length ? arguments[arguments.length - 1] : 'default';
return lastArg;
}
foo(); // "default"
foo(1); // 1
foo(1, 2); // 2
If you want to write a function similar to bind which only sticks arguments on the end then you could do
function appendArguments(fn) {
var slice = Array.prototype.slice.call.bind(Array.prototype.slice),
args = slice(arguments, 1);
return function () {
return fn.apply(this, slice(arguments).concat(args));
};
}
now
var bar = appendArguments(foo, 3);
bar(); // 3
bar(4, 5); // 3 (because it's calling `foo(4, 5, 3)`

Categories