I need to create new objects in an object with a function. It should work this way: I need to collect some data into a big object that consists of some smaller objects that I should create using a function.
It works this way: a user gets a created by my function object, fills it and then this object is pushed to the big object. The problem is I don't totally understand how to create a new object every time because my code just changes data in one object. The creation of the new function should happens only when it's required by a user.
My code:
let ger_tasks = {}
let name = 1;
let descr = 2;
let timing = 3;
function newTask(name,descr,timing) {
this.name = name;
this.descr = descr;
this.timing = timing;
name = {
description:descr,
timings:timing,
}
ger_tasks.name = name;
}
newTask('a','b','c')
newTask('0','1','2')
console.log(ger_tasks)
Thanks in advance!
Here is a snippet of my try on it :
let ger_task = {}
let name = 1;
let descr = 2;
let timing = 3;
function newTask(name,descr,timing) {
this.name = name;
this.descr = descr;
this.timing = timing;
content = {
description:this.descr,
timings:this.timing,
}
ger_task[name] = this.content;
}
newTask('a','b','c')
newTask('0','1','2')
console.log(ger_task)
Use square bracket notation:
ger_tasks[name] = /*varname*/;
Also, don't call your variable name - instead something else so that the parameter is not overwritten
Related
I am running into a problem with using an array as a Javascript field.
var Object = function () {
var admins = [];
this.addAdmin = function(admin){
this.admins.push(admin)
}
}
Normally I would expect admin to be pushed into the array admins but instead I get a 'cannot read property 'push' of undefined'.
If I'm not mistaken when I initialized the Object with new Object(), admins = []; should initialize the array. Is this a limitation of Javascript?
Thank you in advance.
var array creates a local variable. It does not create a property on the object.
You need:
this.admins = [];
or
admins.push(admin) /* without this */
In your function admins is a local variable to the function. You need to declare admins as a property on the instance.
function Obj(){
this.admins = [];
}
Obj.prototype.addAdmin = function(admin){
this.admins.push(admin);
}
obj = new Obj();
obj.addAdmin('tester');
Also, because Object is the global base object, don't create functions or objects named Object.
I suspect you've gotten confused (which is easy :-) ) because you've seen code like this:
class Obj {
admins = [];
addAdmin(admin) {
this.admins.push(admin);
}
}
That uses the modern class and class fields syntax to puts an admins property on the object constructed via new Obj. (Note there's no var before admins = [];.) But in your code, you've used the older function-based syntax. Within your function, var admins = []; just creates a local variable, not a property.
I'd suggest that if you want to create constructor functions, using the new class syntax above is the simpler, more powerful way to do that. If you want to use the older syntax, though, other answers have shown how, but for completeness either make admins a property of the object:
let Obj = function() {
this.admins = []; // ***
this.addAdmin = function(admin){
this.admins.push(admin)
};
};
or perhaps with addAdmin on the prototype:
let Obj = function() {
this.admins = []; // ***
};
Obj.prototype.addAdmin = function(admin){
this.admins.push(admin)
};
or use the fact addAdmins closes over the call to Obj, and thus the local admins:
let Obj = function() {
const admins = [];
this.addAdmin = function(admin){
admins.push(admin) // <=== No `this.` here, you want to close over the
// `admins` local
};
};
I am assumming Object is a placeholder, because it is a reserved keyword.
What is happening is, your variable var admins = []; is created locally and can noot be accesed with the this. as a result when you set the value in this.admins.push(admin) the admins there is undefined. you should modify your function to read this way
var Obj = function () {
this.admins = [];
this.addAdmin = function (admin) {
this.admins.push(admin);
};
};
const object = new Obj();
object.addAdmin(1);
you should not omit the this keyword like this(no pun intended) if you plan to new the function. Stick to the code above.
var Obj = function () {
var admins = [];
this.addAdmin = function (admin) {
admins.push(admin);
};
};
const object = new Obj();
console.log(object)
Edit:
I wanted to be more specific about why I'm doing it this way. The code below is something I've been attempting to get working.
function newClass(self) {
this.invest;
this.interest;
function method1() {
return this.invest + this.interest;
}
}
var newC = new newClass();
newC.invest = prompt("Enter investment");
newC.interest = prompt("Enter interest");
alert(newC.method1());
End Of Edit:
I'm fairly new to the javascript language and can not figure out why my functions are always returning NaN. I have attempted many different fixes but nothing I have tried works. Below is an example.
function investment() {
var iniInvest;
var interest;
return iniInvest + interest;
}
investment.iniInvest = 10;
investment.interest = 20;
console.log(investment())
This returns a NaN. I have attempted creating classes and methods and attempted to parse the variables but they still all return NaN.
Unless the variables values are assigned to the var in the function
var iniInvest = 10;
or args are given
function investment(args1, args2) {
return args1 + args2;
}
console.log(investment(10, 20));
it will return NaN.
I appreciate the help.
You cannot access the variable inside functions like
investment.iniInvest = 10;
investment.interest = 20;
Since, you need that variables globally accessed so you can keep that variables outside the function and initialize them from anywhere in the code:
var iniInvest;
var interest;
function investment() {
return iniInvest + interest;
}
iniInvest = 10;
interest = 20;
console.log(investment())
The code investment.iniInvest = 10; is creating an iniInvest property on investment, not a local variable. This code does not modify the variable var iniInvest created within the function's scope.
function investment() {
return investment.iniInvest + investment.interest;
}
investment.iniInvest = 10;
investment.interest = 20;
console.log(investment())
This code achieves what you are asking, but this is not a good way to solve the problem.
The following is more likely what you are looking for:
function investment( iniInvest, interest) {
this.iniInvest = iniInvest;
this.interest = interest;
this.investment = function() {
return this.iniInvest + this.interest;
};
}
var inv = new investment( 10, 30 );
console.log( inv.investment() );
inv.iniInvest = 5;
inv.interest = 10;
console.log( inv.investment() );
As you are declaring iniInvest interest in function so you can not use that variable out of that function as they are out of scope. Make that variable global.
You can go through https://www.w3schools.com/js/js_scope.asp for scope of variables.
The problem is that when you declare a variable inside of a function, it exists only within that function, and is only local. Therefore, it can not be referenced from outside of the function.
In the example that you gave, you attempt to reference the variable investment.iniInvest and investment.interest, but those variables only exist within the local reference of the investment function, and are destroyed after the function ends, so you can not reference them. You're probably better off using args anyways.
You can try something like
var investment = function () {
this.iniInvest;
this.interest;
this.sum = function() {
return this.iniInvest + this.interest;
}
}
var i = new investment()
i.iniInvest = 10;
i.interest = 20;
console.log(i.sum());
Thanks everyone for all your answers! After reading everyones answer I was able to fix my syntax and resolve the problem.
This is my finished code.
function newClass() {
this.invest;
this.interest;
this.investment = function() {
return parseFloat(this.invest) + parseFloat(this.interest);
}
}
var newC = new newClass();
newC.invest = prompt("Enter investment");
newC.interest = prompt("Enter interest");
alert(newC.investment());
It returns the proper answer. Please do let me know if this code requires fixing.
Thanks Again!
Doing some javascript prototypical inheritance, I would like to push the arguments in my Grades constructor and do the storage manipulation and push the data inside my this.students array using my storage method, and then use the values as I please within my other methods.
But the problem is that when I console log the constructor, it does what I need it to in terms of pushing the data in the this.students array but each object comes up as undefined.
This is weird because if I run the for loop inside the Grades constructor it will work perfectly. But I would like to have a separate method to do this, inside of within my Grades constructor
Any help in pointing me in the right direction would be great! Thanks!
function Grades(studentGrades) {
if(!Array.isArray(studentGrades)) return true;
this.students = [];
this.studentGrades = arguments.length;
this.numRows = 0;
this.numColumns = 0;
this.init();
}
/*
* Method to initialize functions
*/
Grades.prototype.init = function() {
this.storage();
};
/*
* Method to store a list of grades in an array object
*/
Grades.prototype.storage = function() {
for(var i=0; i < this.studentGrades; i++) {
this.students.push(this.studentGrades[i]);
}
};
/*
* Method to add grades
*/
Grades.prototype.addGrades = function(numRows, numColumns, initial) {
for(this.numRows; this.numRows < this.students.length; this.numRows++ ) {
}
};
/*
* Method to display the students average
*/
Grades.prototype.display = function() {
// body...
};
var inputGrades = new Grades( [89,78,93,78], [83,67,93,98], [93,99,73,88] );
console.log(inputGrades);
I think there are some problems with your code, especially with Grades constructor :
function Grades(studentGrades) {
if(!Array.isArray(studentGrades)) return true;
this.students = [];
this.studentGrades = arguments.length;
this.numRows = 0;
this.numColumns = 0;
this.init();
}
You are using an array as parameter to the function but you are passing thtree parameters (arrays), I think this line:
var inputGrades = new Grades( [89,78,93,78], [83,67,93,98], [93,99,73,88] );
Should be like this:
var inputGrades = new Grades( [[89,78,93,78], [83,67,93,98], [93,99,73,88] ]);
And the following line this.studentGrades = arguments.length; is useless in the constructor and may cause problems in your code, and should be replaced with :
this.studentGrades = arguments;
Or if you pass an array of arrays like I did you can use:
this.studentGrades = studentGrades;
Your problem is inside your storage function, originating from definition.
this.studentGrades is actually defined as the length of the array, not the array itself.
If you do not store the input array or pass it on through init(inputGrades) to storage(inputGrades), then you cannot access the original input from your storage prototype.
Better: change constructor bit to:
this.students = [];
this.studentGrades = studentGrades;
And your function inside storage to:
for(var i=0; i < this.studentGrades.length; i++) {
this.students.push(this.studentGrades[i]);
}
And you should be fine I think.
UPDATE: your original function call has a variable number of arguments.
Simplest way to get to complete answer is to change argument variable to:
var inputGrades = new Grades( [[89,78,93,78], [83,67,93,98], [93,99,73,88]]);
Now you send only one argument, an array of arrays.
Alternative: change the function to
function Grades() { // so no input argument
if(!Array.isArray(studentGrades)) return true;
this.students = [];
this.studentGrades = Array.prototype.slice.call(arguments);
this.numRows = 0;
this.numColumns = 0;
And then you should be able to send in multiple arguments.
I'm having trouble getting my function to increment user id on the creation of every new object, but also preventing other functions from changing it.
function User(u_name) {
this.user_name = u_name;
this.user_id = User.next_user_id++;
}
User.next_user_id = 1;
user1 = new User('john');
user2 = new User('jane');
if I move next_user_id into function User as var next_user_id then it gets reset on every new object, which is not what I want.
How can I increment user_id for every new object but prevent other functions from changing it?
you should try looking up closures...
var User = (function()
{
var next_user_id = 1;
return function(u_name)
{
this.user_name = u_name;
this.user_id = next_user_id++;
}
})()
user1 = new User('john');
user2 = new User('jane');
You need to attach the variable to the function's prototype.
Try:
User.prototype.next_user_id = 1;
If you want to control access to (C# like) internal only, you need to turn it into a property.
var $Mynamespace$User$Count = 0;
function $Mynamespace$User$IncrementUser() {
$Mynamespace$User$Count++;
};
var User = function(name){
this.name = name;
$Mynamespace$User$IncrementUser();
};
User.prototype = {
GetUserCount: function() { return $Mynamespace$User$Count; }
};
var jane = new User("jane");
var john = new User("john");
alert(User.prototype.GetUserCount());
alert(jane.GetUserCount());
Let's say I have some class called loopObject and I initialize every object through something like var apple = new loopObject(); Is there anyway to loop through all objects of a class so that some function can be performed with each object as a parameter? If there isn't a direct method, is there a way to place each new object into an array upon initialization?
You can make an array that contains every instance, like this:
function LoopObject() {
LoopObject.all.push(this);
}
LoopObject.all = [];
However, it will leak memory - your instances will never go out of scope.
function loopObject(){
this.name = 'test'
};
var list = [], x = new loopObject, y = new loopObject;
list.push(x)
list.push(y)
for ( var i = list.length; i--; ) {
alert( list[i].name )
}
var allObjects [] = new Array();
function loopObject() {
...
allObjects.push(this);
}
Then one can loop through all elements of allObjects as necessary using allObjects.length.