I'm trying hard to understand basic concepts of javascript. The code below seems to be working fine if I use only "gear += 1" in line 8 below, but I cannot understand why is this not working when I'm using "this.gear += 1". It gives result as NaN. Thank you.
(function bike(speed, tank, gear) {
var i = {};
i.speed = speed;
i.tank = tank;
i.gear = gear;
i.addgear = (function() {
// works fine with "return gear+= 1" Why not with "this"?
return this.gear += 1;
})();
console.log("mybike", i);
})(120, 12, 5);
There are many ways to achieve what you're looking for, including the class keyword from ES2015 and up or the prototype system that underlies it. Here's a very simple sample:
function bike(speed, tank, gear) {
return {speed, tank, gear, addGear: function() {return this.gear += 1}}
}
const myBike = bike(120, 12, 5)
console.log(myBike);
myBike.addGear();
console.log(myBike)
Yours doesn't work for several reasons. First of all, you never return anything out of your outermost function. Secondly, you create and immediately execute a function whose output then becomes your addGear value. The simplest fix to your code would be something like this:
function bike(speed, tank, gear) {
var i = {};
i.speed = speed;
i.tank = tank;
i.gear = gear;
i.addgear = function() {
return this.gear += 1;
};
return i;
}
That would be equivalent to what I wrote above.
Related
I have been working all day trying to pass the value of "returnData.salary" inside the "readData" function to
the object inside the "calculateTax" function which is suppose to take the salary value and calculate state and federal taxes. I am stumped, I can't find anything on the internet which provides a good example for me to work with. The examples are either way to simple or super complex. Any help would be appreciated.
I apologize in advance if I did not submit this question in the correct format. This is my first time asking for help on stackoverflow.
function readForm() {
var returnData = {};
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
$("#name2").text(returnData.name);
$("#lastName2").text(returnData.lastName);
$("#age2").text(returnData.age);
$("#gender2").text(returnData.gender);
$("#salary2").text(returnData.salary);
$("#myTextArea2").text(returnData.myTextArea);
if ($(isManager).is(':checked')) {
$("#isManager2").text("Yes");
}
else {
$("#isManager2").text("No");
}
//$("#employeeForm")[0].reset();
} //end of readForm function
function calculateTax() {
console.log("Button Works");
var calculateTax = {
state: function(num) {
num *= 0.09;
return num;
}
, federal: function(num) {
if (num > 10000) {
num *= 0.2;
return num;
}
else {
num * 0.1;
return num;
}
}
, exempt: true
};
}
//Invoke readForm function when the submit button is clicked.
$(document).ready(function () {
$("#btnSubmit").on("click", readForm);
$("#btnCalculate").on("click", calculateTax);
})
</script>
Well, simply put; you can't. Not like this anyway. Or, at least not pass the value to the function directly.
You are using global functions right now, which are not inside a class. If it was inside a class, you could instantiate the class and save it to this (which would be the class' instance). However, I'm assuming classes are a bit over complicated in this case. What you could do, is set variables globally so all functions can use them, like this;
//declare the global variable so it exists for every function
var returnData = {};
function readForm() {
//We do NOT redeclare the "var" again. It's global now.
returnData = {}; //Reset the global variable when this function is called
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
//Rest of your function
}
function calculateTax(){
console.log(returnData) //works here
}
Note that you do overwrite global variables, so it's best to reset them on every function call. You might get old data stuck in there, otherwise.
I recently had to refactor a chunk of javascript that is using YUI.
So, originally it was something like this:
YAHOO.namespace('space.time');
YAHOO.space.time = (function() {
var b = document.getelementbyid("aifdsgyalierg");
function c(b) {
var a = new YAHOO.util.Anim(d, b); //just assume the parameters are correct here
a.method = YAHOO.util.Easing.easeOut;
a.animate();
};
return { c:c };
})();
For the sake of being able to inject dependencies, i refactored it to the below:
YAHOO.namespace('space.time');
YAHOO.namespace('space.timefn');
YAHOO.space.timefn = function(yuianim) {
var b = document.getelementbyid("aifdsgyalierg");
function c(d) {
var a = new yuianim(d, b); //just assume the parameters are correct here
a.method = YAHOO.util.Easing.easeOut;
a.animate();
};
return { c:c };
};
YAHOO.space.time = YAHOO.space.timefn(YAHOO.util.Anim);
So..
1) Ignoring any committed fallacies.. Will the behaviour of the two snippets differ?
2) What fallacies have i committed?
I'm working on some script for a set of functions that all operate from one call and take a large number of parameters to return one value. The main function requires the use of 11 other functions which need to work with the same parameters. I have it structured somewhat like this:
function mainfunction(param1, param2, ..., param16)
{
//do a bunch of stuff with the parameters
return output;
}
function secondaryfunction1()
{
//gets called by mainfunction
//does a bunch of stuff with the parameters from mainfunction
}
Is there anything I can do to make the parameters passed to mainfunction available to all the secondary functions without passing them or making them global variables? If not, that's fine, I'll pass them as parameters - I'm curious as to whether or not I can do it more elegantly.
You can place the definition of secondaryfunction1 inside mainfunction:
function mainfunction(param1, param2, ..., param16){
function secondaryfunction1() {
// use param1, param2, ..., param16
}
secondaryfunction1();
}
Update:
As #dystroy pointed out, this is viable if you don't need to call secondaryfunction1 somewhere else. Where the list of parameters would be coming from in this case - I don't know.
You could use arguments to pass to secondaryFunction1 all the arguments of mainfunction. But that would be silly.
What you should probably do, and what is usually done, is embed all the parameters in an "options" object :
function mainfunction(options){
secondaryfunction1(options);
}
function secondaryfunction1(options) {
// use options.param1, etc.
}
// let's call it
mainfunction({param1: 0, param2: "yes?"});
This leds to other advantages, like
naming the parameters you pass, it's not a good thing for maintenance to have to count the parameters to know which one to change. No sane library would let you pass 16 parameters as direct unnamed arguments to a function
enabling you to pass only the needed parameters (the other ones being default)
#Igor 's answer (or some variation) is the way to go. If you have to use the functions elsewhere, though (as #dystroy pointed out), then there is another possibility. Combine your parameters together into an object, and pass that object to the secondary functions.
function combineEm() {
// Get all parameters into an array.
var args = [].slice.call(arguments, 0),
output = {},
i;
// Now put them in an object
for (i = 0; i < args.length; i++) {
output["param" + i] = args[i];
}
return output;
}
From your main function, you can do:
function mainfunction(param1, param2, ..., param16) {
var params = combineEm(param1, param2, ..., param16);
var output = secondaryfunction(params);
// etc.
return output;
}
Edit: I just wanted to clarify that all of the proposed suggestions so far do work. They just each have their own trade-offs/benefits.
I tried just suggesting some changes to other answers, but ultimately I felt like I needed to just post my solution to this.
var externalFn = function(options) {
var str = options.str || 'hello world';
alert(str);
};
var main = function(options) {
var privateMethod = function() {
var str = options.str || "foobar";
alert("str: " + str);
};
// Bind a private version of an external function
var privateMethodFromExternal = externalFn.bind(this, options);
privateMethod();
privateMethodFromExternal();
};
main({ str: "abc123"});
// alerts 'str: abc123'
// alerts 'abc123'
main({});
// alerts 'str: foobar'
// alerts 'hello world'
It seems like the main point of the question is that the functions used by the 'main function' shouldn't have to keep having the options/context passed to them.
This example shows how you can use privateMethods inside the function
It also shows how you can take external functions (that you presumably use outside of main) and bind a private method version of them for use inside main.
I prefer using some sort of 'options' object, but that aspect isn't really that important to the question of scoping that the OP was really asking about. You could use 'regular' parameters as well.
This example can be found on codepen.
Here's an incredibly naughty solution, if you're interested in that sort of thing.
var f1 = function() {
var a = 1;
var _f2 = f2.toString().replace(/^function[^{}]+{/, '');
_f2 = _f2.substr(0, _f2.length - 2);
eval(_f2);
}
var f2 = function(a) {
var a = a || 0;
console.log(a);
}
f2(); // logs 0
f1(); // logs 1
It executes the contents of some external function entirely in the current scope.
However, this sort of trickery is almost definitely an indicator that your project is mis-organized. Calling external functions should usually be no more difficult than passing an object around, as dystroy's answer suggests, defining the function in-scope, as Igor's answer suggests, or by attaching some external function to this and writing your functions primarily against the properties of this. Like so:
var FunLib = {
a : 0,
do : function() {
console.log(this.a);
}
}
var Class = function() {
this.a = 1;
this.do = FunLib.do;
this.somethingThatDependsOnDo = function() {
this.a++;
this.do();
}
}
var o = new Class();
FunLib.do() // 0
o.do() // 1
o.somethingThatDependsOnDo(); // 2
o.do() // 2 now
Similarly, and possibly better-solved with a class hierarchy.
function BasicShoe {
this.steps_taken = 0;
this.max_steps = 100000;
this.doStep = function() {
this.steps_taken++;
if (this.steps_taken > this.max_steps) {
throw new Exception("Broken Shoe!");
}
}
}
function Boot {
this.max_steps = 150000;
this.kick_step_equivalent = 10;
this.doKick = function() {
for (var i = 0; i < this.kick_step_equivalent; i++) {
this.doStep();
}
}
}
Boot.prototype = new BasicShoe();
function SteelTippedBoot {
this.max_steps = 175000;
this.kick_step_equivalent = 0;
}
SteelTippedBoot.prototype = new Boot();
I'm trying to translate a PHP class into JavaScript. The only thing I'm having trouble with is getting an item out of an array variable. I've created a simple jsfiddle here. I cannot figure out why it won't work.
(EDIT: I updated this code to better reflect what I'm doing. Sorry for the previous mistake.)
function tattooEightBall() {
this.subjects = ['a bear', 'a tiger', 'a sailor'];
this.prediction = make_prediction();
var that = this;
function array_random_pick(somearray) {
//return array[array_rand(array)];
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*somearray.length)];
return random;
}
function make_prediction() {
var prediction = array_random_pick(this.subjects);
return prediction;
}
}
var test = tattooEightBall();
document.write(test.prediction);
Works fine here, you are simple not calling
classname();
After you define the function.
Update
When you make a call to *make_prediction* , this will not be in scope. You are right on the money creating a that variable, use it on *make_prediction* :
var that = this;
this.prediction = make_prediction();
function make_prediction() {
var prediction = ''; //initialize it
prediction = prediction + array_random_pick(that.subjects);
return prediction;
}
You can see a working version here: http://jsfiddle.net/zKcpC/
This is actually pretty complex and I believe someone with more experience in Javascript may be able to clarify the situation.
Edit2: Douglas Crockfords explains it with these words:
By convention, we make a private that variable. This is used to make
the object available to the private methods. This is a workaround for
an error in the ECMAScript Language Specification which causes this to
be set incorrectly for inner functions.
To see the complete article head to: http://javascript.crockford.com/private.html
You never call classname. Seems to be working fine.
Works for me:
(function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
function pickone(somearray) {
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*length)];
return random;
}
var random_item = pickone(this.list);
document.write(random_item);
}());
Were you actually calling the classname function? Note I wrapped your code block in:
([your_code]());
I'm not sure what you're trying to accomplish exactly with the class structure you were using so I made some guesses, but this code works by creating a classname object that has instance data and a pickone method:
function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
this.pickone = function() {
var length = this.list.length;
var random = this.list[Math.floor(Math.random()*length)];
return random;
}
}
var cls = new classname();
var random = cls.pickone();
You can play with it interactively here: http://jsfiddle.net/jfriend00/ReL2h/.
It's working fine for me: http://jsfiddle.net/YznSE/6/ You just didn't call classname(). If you don't call it, nothing will happen ;)
Make it into a self-executing function like this:
(function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
function pickone(somearray) {
var length = somearray.length; //<---WHY ISN'T THIS DEFINED??
var random = somearray[Math.floor(Math.random() * length)];
return random;
}
var random_item = pickone(this.list);
document.write(random_item);
})();
var test = tattooEightBall();
document.write(test.prediction);
Should be:
var test = new tattooEightBall(); //forgot new keyword to create object
document.write(test.prediction()); // forgot parens to fire method
and:
this.prediction = make_prediction();
Should be:
this.prediction = make_prediction;
First off, I am sorry if this is a duplicate, but every time I googled for 'object' and 'code' I got tutorial pages.
I want to know if there is any easy way to get the code associated with an object. Something like
function A(){
this.name = 'Kaiser Sauze';
}
a = new A();
console.log(a.displayCode());
//OUTPUT
"function A(){ this.name = 'Kaiser Sauze';}"
I want to be able to view the code, modify it and reload the function, all from within the browser. I wanted to know if there was some way to do this, or if I have to prime the pump by doing something like this:
function A(){
this.name = 'Kaiser Sauze';
this.code = "function A(){ this.name = 'Kaiser Sauze';}"
}
then every time the user loads up the text editor to view this.code I connect the onchange to update this.code.
EDIT
turns out yankee suggested a simple solution to this
function A(x){
this.x = x ;
}
console.log(A.toString());
//OUTPUT
"function A(x){
this.x = x ;
}"
but in my implementation the variable 'x' can be a function (actually a complicated object with variables, functions and sub objects which I mix in via a call to dojo.mixin), so what I really want is to know the code when instantiated, something like so
function A(x){
this.x = x ;
}
var a = new A(function(){/*DO SOMETHING*/);
console.log(a.toString());
//OUTPUT
"var a = new A(function(){/*DO SOMETHING*/);"
but, as most of you already know, all that gets output is something like "Object". I have almost found a way around this, by putting the initialization in a function like so
function A(x){
this.x = x ;
}
function _A(){
var a = new A(function(){/*DO SOMETHING*/);
}
console.log(_A.toString());
//OUTPUT
"function _A(){
var a = new A(function(){/*DO SOMETHING*/);
}"
but that is confusing, and then I have to go in and start parsing the string which I do not want to do.
EDIT: The reason I ask all of this is b/c I want to make code that is both dynamically executable and highly modular. I am dealing with the canvas. I want the user to be able to click on a, for example, rectangle, view its code, and modify and then load/execute it. I have a series of rules but basically I have a shape class and everything that defines that shape (color, transparency, fills, strokes...) has to get passed as a parameter to the object cosntructor, something like:
rect = new Shape({color : 'rgba(0,0,0,1)' ,
x : 0 ,
y : 0 ,
w : 100 ,
h : 100 ,
draw : function() {ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.w,this.h);
}
});
This way the code is automatically modular, I don't have to worry about the color being defined at the top of the page, and then the height being defined half way down the page, and so on. Now the only thing I need is to somehow, pass as a parameter, the entire above string representation of the initialization. I could wrap it in a function and call toString on that, like so
function wrapper(){
rect = new Shape({color : 'rgba(0,0,0,1)' ,
x : 0 ,
y : 0 ,
w : 100 ,
h : 100 ,
draw : function() {ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.w,this.h);
},
code : wrapper.toString()
});
}
but then there are two problems. 1) I have to manually remove the function wrapper() and trailing } as well as moving every line to the left by one tab. 2) there is no guarantee that a user will remember to include the wrapper function as it is totally unecessary for purposes of drawing. I am trying to think of a way where the wrapper would seem natural, but I can't think of any. But then again I haven't slept in over 30 hours.
OK... Reviewing again... I think that's what you want ;-).
>>> function A() {this.name ="foo";}
undefined
>>> A.toString()
"function A() {this.name ="foo";}"
Refer to code snippet below:
function A() {
this.name = 'Kaiser Sauze';
}
a = new A();
console.log(a.constructor.toString());
// output
// "function A(){
// this.name = 'Kaiser Sauze';
// }"
When you do new A(), function A becomes the constructor of object a. Thus, you can reference function A via the constructor property of object a.
Read more about Javascript constructor on MDN.
Edit: added pretty-printing.
You could JSON.stringify() the argument of the constructor, if it is JSON-compatible. Here is a toString() function that builds on this idea, but with a slightly generalized version of JSON.stringify() that accepts stringifying functions:
function Shape(x){
this.x = x;
}
Shape.prototype.toString = function() {
function stringify(data, prefix) {
function unicode_escape(c) {
var s = c.charCodeAt(0).toString(16);
while (s.length < 4) s = "0" + s;
return "\\u" + s;
}
if (!prefix) prefix = "";
switch (typeof data) {
case "object": // object, array or null
if (data == null) return "null";
var i, pieces = [], before, after;
var indent = prefix + " ";
if (data instanceof Array) {
for (i = 0; i < data.length; i++)
pieces.push(stringify(data[i], indent));
before = "[\n";
after = "]";
}
else {
for (i in data)
pieces.push(i + ": " + stringify(data[i], indent));
before = "{\n";
after = "}";
}
return before + indent
+ pieces.join(",\n" + indent)
+ "\n" + prefix + after;
case "string":
data = data.replace(/\\/g, "\\\\").replace(/"/g, '\\"')
.replace(/\n/g, "\\n").replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/[\x00-\x19]/g, unicode_escape);
return '"' + data + '"';
default:
return String(data).replace(/\n/g, "\n" + prefix);
}
}
return "new Shape(" + stringify(this.x) + ")";
};
var rect = new Shape({color : 'rgba(0,0,0,1)' ,
x : 0 ,
y : 0 ,
w : 100 ,
h : 100 ,
draw : function() {ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.w,this.h);
}
});
console.log(rect.toString());
The output is:
new Shape({
color: "rgba(0,0,0,1)",
x: 0,
y: 0,
w: 100,
h: 100,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
}
})
I can't believe no one suggested this (I apologize if this answer is somewhere in between the lines). I didn't think of it because at the time of development, all my work was clientside. All I really have to do is load the code once with Ajax as javascript. Once it is loaded and an object created, I load it again as a string and assign it to a variable in the object.
Here is another solution that might work (using yankee's example). I am however unsure what happens if A already exists? Perhaps you should do a "delete(A);" before saving it in the storage.
// Create A
// function A() {this.name = "foo";}
var x = 'function A() {this.name = "foo";}'; // Store function to variable using A.toString();
// Save x in storage
// -- Page reload --
// Load and eval x from storage
eval(x);
var a = new A(); // Use A
alert(a.name);
function dumpObject(obj)
{
var output = "";
for (var i in obj)
{
var msg = i + "= " + obj[i];
output += msg + "\n";
}
return output;
}
var myObject = {
myName: 'Daniel',
get_name: function()
{
return this.myName;
}
}
alert( dumpObject(myObject) );
//this will output:
//
// myName= Daniel
// get_name=function()
// {
// return this.myName;
// }
Here is my fiddle for that:
http://jsfiddle.net/DanielDZC/vXrQf/
I wouldn't recommend using on a production server, only for testing and debugging, but there is a method named toSource() which returns the source of a function as a String:
function add(a, b) {
return a + b;
}
console.log(add.toSource());
Outputs:
function add(a, b) { return a + b; }
Available on JS Fiddle: http://jsfiddle.net/IQAndreas/dP453/1/
Note that Mozilla has marked this method as non-standard (which if you read the details means "Only works in FireFox").
Sounds like you're looking for Reflection and/or Introspection support. I'm not sure where the other major engines are at in this regards but SpiderMonkey's Parser API was recently referenced in an article on Extension Introspection with Chrome Privileges.