passing an object to a function in javascript - javascript

This might seem like a noob question but I'm not sure what to do. I have function with 2 variables.
function someInfo(myVar1,myVar2)
{
this.lmyVar1=myVar1;
this.myVar2=myVar2;
}
myInstance=new someInfo("string1","string2");
function drawVariables(){
document.write(myInstance.myVar1);
document.write(myInstance.myVar2);
}
I want to use the same drawVariable() for multiple instances. I just can't figure out how the exact syntax for that. How can I make drawVariable() use a different instance of someInfo without repeating anything? Is there a simple example or tutorial I can follow?

Add an argument to the definition of function drawVariables. In the code below, this argument is called info. Now you can use info as your object inside the drawVariables function, and while calling drawVariables function, you can pass whatever instance you want to pass it. drawVariables function would now work with whatever instance you pass it while calling.
function someInfo(myVar1,myVar2)
{
this.myVar1=myVar1;
this.myVar2=myVar2;
}
// Create two separate instances
myInstance=new someInfo("string1", "string1");
myInstance2 = new someInfo("string2", "string2");
// info is the argument that represents the instance passed to this function
function drawVariables(info){
alert(info.myVar1 + ", " + info.myVar2);
}
// Call the function twice with different instances
drawVariables(myInstance);
drawVariables(myInstance2);
See http://jsfiddle.net/WLHuL/ for a demo.

function drawVariables(instance){
document.write(instance.myVar1);
document.write(instance.myVar2);
}

Would it make sense for you to do it this way?
function someInfo(myVar1, myVar2)
{
this.lmyVar1 = myVar1;
this.myVar2 = myVar2;
this.drawVariables = function ()
{
document.write(this.lmyVar1);
document.write(this.myVar2);
}
}
function Test()
{
var obj1 = new someInfo("aaa", "bbb");
var obj2 = new someInfo("xxx", "zzz");
obj1.drawVariables();
obj2.drawVariables();
}

Related

Is it possible to name a function using arguments passed from another function?

I'm a complete newbie to Javascript so I don't know what its capable of. Any help would be much appreciated!
As the title suggests, I'm trying to pass an argument from a function to name another function inside of it. The method below doesn't work for obvious reasons but I think it conveys what I'm trying to do. The function names need to be very specific for the project I'm working on.
function mainFunc(param1) {
function param1() {}
}
Thanks!
Edit: The software that we are going to start using to go paperless at my work uses a javascript scripting engine. In order for me to do simple things such as:
If at least one of the checkboxes in section A is checked, then you must check at least one checkbox in section B.
I would have to write a function for each and every checkbox field on the form due to the way the software works, the function name has to be specific to the name we assign to the checkbox through their GUI. I was hoping to write a function that writes another function with the specific name, and calls the said function.
function mainFunc(funcName) {
function 'funcName'() {
//do stuff;
}
'funcName'()
}
mainFunc('Checkbox1')
Maybe this will help clarify a little more on what I'm trying to do. Sorry for not being clear the first time around.
You have many options to solve your problem
one option is to return an object with the functions named using the parameters passed to mainFun look at the example below
function mainFunc(param1,param2) {
return {
[param1]:function () {
console.log(" I am function from " + param1)
},
[param2] : function () {
console.log("I am function from " + param2) ;
}
}
}
let hello = 'hello' ;
let greet = 'anything' ;
let functions = mainFunc(hello,greet);
functions['hello']();
functions['anything']();
functions[hello]();
functions[greet]();
if you have many parameters to the mainFun you can also solve it using the arguments object like the example below
function mainFun(par1) {
let myObj = {};
for(let i = 0 ; i<arguments.length;i++){
console.log(arguments[i]);
myObj[arguments[i]] = ()=> {
console.log('You call me from ' + arguments[i]);
}
}
return myObj ;
}
let functions = mainFun('a','b','c','d');
functions['a']();
functions['b']();
functions['c']();
functions['d']();

attache function to other function in javascript

I have a simple requirement, I need add the same code to hundreds of other JavaScript functions, the code can be executed at the end of the function, is there a handy way of doing it, like attach an function to another function dynamically, I think yes, because JavaScript is so powerful and too powerful, any ideas?
Note, I need dynamically assign new code or function to existing functions without change existing function's code, please give a solid solution, I can do it in hacky way, but no hacky way please!
The first method that comes to mind is simply create another function:
function primaryFunction() {
// ...
utilityMethod();
}
function otherPrimaryFunction() {
// ...
utilityMethod();
}
function utilityMethod() { ... }
Now utilityMethod() gets called from the end of each other primary function.
There's also a method which requires more code refactoring but is better in the long term: classes/prototypes.
Essentially, you have one "constructor" function which takes a number of parameters for the "class" and returns an class-like object:
function constructor(someClassField, anotherField) {
this.aField = someClassField;
this.fieldTwo = anotherField;
return this;
}
Now if you call this and pass some parameters, you get a class out:
var myClass = new constructor("1", "2");
myClass.aField == "1";
myClass.fieldTwo == "2";
So: If you define your utility method as above, then you can use this: for every primary function you instantiate a new instance of the constructor, with the final code looking like this:
function constructor(primaryFunction) {
this.function = primaryFunction;
this.call = function() {
this.function();
utilityMethod();
}
this.call();
return this;
}
function utilityMethod() { ... }
var primaryMethod = new constructor(function() { ... });
The creation of primaryMethod now automatically calls the primary function followed by the utility method, before returning the object so you can re-call both if you want to.

jQuery + Javascript - accessing object fields in anonymous function

I'm not into JavaScript OOP, so I've made an object with some fields which contains some functions to invoke.
var test = {
questions: [],
addQuestion: function(questionTitle, possibleAnwsers)
{
// not really important
},
appendQuestionToHTML: function(question)
{
// not really important
},
makeQuestionFieldsEditable: function($questionNode)
{
$questionNode.find(".questionTitle").first(function(){this.changeTextOnClick($(this));});
$questionNode.find(".questionChoice").each(function(){this.changeTextOnClick($(this));});
},
changeTextOnClick: function($spanElement)
{
// not really important
}
};
Following object in makeQuestionFieldsEditable() function looks for ".questionTitle"-class node and all of ".questionChoice"-class nodes invoke another function for them.
The problem is that using this in anonymous function references to itself, not function saved on field changeTextOnClick.
Javascript/JQuery wants to invoke this function on HTMLDivElement, which doesn't exists.
Is there any solution?
You can do the trick using a reference to your this variable :
makeQuestionFieldsEditable: function($questionNode)
{
var that = this;
$questionNode.find(".questionTitle").first(function(){that.changeTextOnClick($(this));});
$questionNode.find(".questionChoice").each(function(){that.changeTextOnClick($(this));});
},
I think all you need to do is change 'this' to 'test' (the variable you have assigned this object to).

Javascript Class Inheritance

Can anyone tell me why my 'showDiv_boo' is undefined inside the class´s method?
I also can´t access my class´s methods.
Here´s my class 'Blink' class with its properties and methods:
function Blink(div) {
this.div = div
}
Blink.prototype.counter = 0
Blink.prototype.showDiv_boo = true
Blink.prototype.showDiv = function() {
this.div.style.visibility = 'visible'
}
Blink.prototype.hideDiv = function() {
this.div.style.visibility = 'hidden'
}
Blink.prototype.startEngine = function() {
if (this.showDiv_boo) {
this.showDiv()
} else if (!this.showDiv_boo) {
this.hideDiv()
}
this.showDiv_boo = !this.showDiv_boo
this.counter++
}
Blink.prototype.startEffect = function() {
this.idEffect = setInterval(this.startEngine, 1000 / 45)
}
So, if I create:
_blink = new Blink(myDiv);
_blink.startEffect();
You can test... the variable 'showDiv_boo', is undefined inside the method.
Even, if I set the showDiv_boo inside the method to true, it won´t call my class´s methods showDiv or hideDiv.
Anyone?
Thanks :)
The reason why is that startEngine is called from setInterval. The way in which this callback is invoked causes startEngine to have a different value for this than startEffect. You need to save this in order to maintain it in the callback. For example.
Blink.prototype.startEffect = function () {
var self = this;
self.idEffect = setInterval(function () { self.startEngine(); }, 1000 / 45);
};
You need to:
use var self and call the method via self.startEngine()
use an anonymous function to wrap the call in [1] i.e. function(){ self.startEngine(); }
This is because when you just pass this.startEngine or self.startEngine you are just passing the function startEngine without specifying what this is, which in both cases is supplied by the global conext of DOMWindow.
To give an example...
function startEngine() {
...code omitted...
};
Blink.prototype.startEngine = startEngine;
Blink.prototype.start = function() {
setTimeout(startEngine, 0); // obviously wrong, what is this?
setTimeout(Blink.startEngine, 0); // actually the same as line above, although not as obvious
setTimeout(startEngine.bind(this), 0); // works correctly
}
works to add code to the prototype and if used in the anonymous function will work as expected, but if you just use Blink.startEngine as the callback it is exactly the same as using startEngine only the second is more obviously wrong because there's no object it is being called on so you'd expect this to be whatever is supplied by the context.
The other way you could do this without using the anonymous function would be
Blink.startEngine.bind(self)
Which returns a function that will call startEngine with the correct this same as explicitly creating the anonymous function and wrapping the call to self.startEngine()
Heres a link to a fiddle to play around with the differences: http://jsfiddle.net/bonza_labs/MdeTF/
If you do the following, you will find it is defined
var x = new Blink('hello');
x.showDiv_boo
Javascript uses prototypical inheritance. While showDiv_boo may not be explicitly defined within the instance of Blink that you now have, it does exist within the prototype that Blink inherits from. When you try referencing showDiv_boo from within the object, the Javascript engine realizes the object does not own a member by that name and then will check its prototype.
Along with setting a temporal variable to store this, you must call the startEngine() function with that variable:
Blink.prototype.startEffect = function(){
var self = this;
self.idEffect = setInterval(function(){ self.startEngine.call(self); }, 1000/45);
}
Note the .call(self), which basically calls the function with the variable self, so the variable this in startEngine will be the correct one.

How to change the order of which they are called?

I have a quite inconvenient problem.
Say that I have the following functions
function name(namearg){
...
..
}
function handlefailed(){
..
..
}
function handlecover(){
..
..
}
Now to my problem, I have alot of hard coded html that can't be changed that is calling both functions like this
Link
Link
Link
The problem is the order of which I'm calling the functions, I first want to see which function that is called, either handlefailed() or handlecover(), and then want to know what name that is sent to the name function.
If I would have called the functions in the other way around I would just have done
var theName;
function name(namearg){
theName = namearg
}
function handlefailed(){
callOtherfunctionInAnotherJavascript(getElements(theName + ".failed"));
}
function handlecover(){
callOtherfunctionInAnotherJavascript(getElements(theName + ".cover"));
}
But now this is not possible since I'm calling the name function after the first function.
Is there a way in javascript that "changes" the order of how the functions are evaluated, or do you guys have a clever sollution to my problem, I.E getting the value of the namearg variable and use it in the handlefailed() & handlecover() functions?
var postFix;
function name(namearg){
callOtherfunctionInAnotherJavascript(getElements(namearg + postFix));
}
function handlefailed(){ postFix = '.failed'; }
function handlecover(){ postFix = '.cover'; }
you can empty both functions:
function handlefailed(){
..
..
}
function handlecover(){
..
..
}
and create two new functions that doing what you need
function handlefailed2(){
..
..
}
function handlecover2(){
..
..
}
then call the new functions from inside function name(namearg) according namearg deside to which function you want to call
You can declare another global, handleFunc, and have handlefailed/handlecover assign which one to call in name.
var theName;
var handleFunc = null;
function name(namearg)
{
if(handleFunc instanceof Function)
{
handleFunc(namearg);
handleFunc = null;
}
theName = namearg
}
function handlefailedCallback(namearg){ /* some code */}
function handlefailed()
{
handleFunc = handlefailedCallback;
}
function handlecoverCallback(namearg){ /* some code */}
function handlecover()
{
handleFunc = handlecoverCallback;
}
This gives you the flexibility to continue using name without breaking other areas of the code.

Categories