I have an object constructor such as:
function myObjConstr () {
console.log(object_name);
}
I want this results:
var name1 = new myObjConstr(); //print in console log "name1"
var nameff = new myObjConstr(); //print in console log "nameff"
You would need to pass the object name to the constructor:
function myObjConstr (obj_name) {
this.object_name = obj_name;
console.log(this.object_name);
}
var name1 = new myObjConstr("name1");
var nameff = new myObjConstr("nameff");
you can make a function constructor myObjConstr(), thenafter you can make new myObjConstr().
1) function constructor
function myObjConstr (objName) {
this.objName = objName;
}
2) make object of type myObjConstr
var name1 = new myObjConstr("name1");
var name2 = new myObjConstr("name2");
3) if you want to print the value,
console.log(name1.objName)
You can't pass the variable name to the constructor. Instead you can convert an array of names of variables to array of objects
let names = [
'name1',
'nameff'
]
let objects = names.map(name => myObjConstr(name));
function myObjConstr(name){
this.name = name;
console.log(this.name);
}
Related
trying to solve the following problem.
I have a construction function like:
function Person (name){
this.firstName = name;
}
than I make some objects:
var myFather = new Person("John");
var myMother = new Person("Mary");
var myChild = new Person ("Sonny");
and finally attach them together:
var family = [myFather, myMother, myChild];
Now I would like to attach a method driver() to 'family', that will use the 'firstName' variable from the constructor function to choose, who is going to drive
Use another class Family and add a setDriver method to it:
function Person (name){
this.firstName = name
}
function Family (members){
this.members = members;
this.driver = members[0];
this.setDriver = function(name){
this.driver = this.members.filter(member => member.firstName == name)[0]
}
}
var myFather = new Person("John");
var myMother = new Person("Mary");
var myChild = new Person ("Sonny");
var family = new Family([myFather, myMother, myChild]);
console.log(family.driver)
family.setDriver("Sonny")
console.log(family.driver)
// At first you should remove comma from you Person function, and use semicolon(;)
// Just create function
function driver(firstName = this.firstName) {
console.log(`Drive is ${firstName}`)
}
driver.call(this, family[0].firstName)
// Result Drive is John
// or you can directly call driver function as method of any family object like
driver.call(family[0])
// Above code will produce same result, please try this
Lets say I get this from an API:
var _persons = [
{
name: 'John'
},
{
name: 'Sarah'
}
];
Now I want to add a greeting function. I want to save memoryspace so I create a Person 'class' and add the function as a proto.
function Person(person){
this.person = person;
}
Person.prototype.greeting = function(){
return 'hello ' + this.person.name
};
I instantiate each person:
var persons = [];
function createPersons(people){
for(var i = 0;i<people.length;i++){
var person = new Person(people[i]);
persons.push(person);
}
};
createPersons(_persons);
Problem is this:
console.log(persons[0].name) //undefined
console.log(persons[0].person.name) //'John'
Is there anyway I can get the first console.log to work?
https://jsbin.com/zoqeyenopi/edit?js,console
To avoid the .person appearing in the object you need to copy each property of the source plain object directly into the Person object:
function Person(p) {
this.name = p.name;
...
}
[or use a loop if there's a large number of keys]
You've then got a mismatch between the named parameter and the variable you're iterating over in the createPersons function. Additionally it would make more sense to have that function return the list, not set an externally scoped variable:
function createPersons(people) {
return people.map(function(p) {
return new Person(p);
});
}
var persons = createPersons(_persons);
NB: the above uses Array.prototype.map which is the canonical function for generating a new array from a source array via a callback.
Loop over all the keys in your object argument and assign them to this
function Person(person){
for (var key in person) {
this[key] = person[key];
}
}
var persons = [];
function createPersons(people){
for(var i = 0;i<people.length;i++){
var person = new Person(people[i]);
persons.push(person);
}
};
createPersons(_persons);
Should be using people as a variable
You're creating a Person object that is given a variable person. You need to change the value you're getting by replacing
var person = new Person(people[i]);
with
var person = new Person(people[i]).person;
var _persons = [
{
name: 'John'
},
{
name: 'Sarah'
}
];
function Person(person){
this.person = person;
}
Person.prototype.greeting = function(){
return 'hello ' + this.person.name;
};
var persons = [];
function createPersons(people){
for(var i = 0;i<people.length;i++){
var person = new Person(people[i]).person;
persons.push(person);
}
};
createPersons(_persons);
console.log(persons[0].name); // logs 'John'
document.write('John');
I'm building an object in javascript to store data dynamically.
Here is my code :
var id=0;
function(pName, pPrice) {
var name = pName;
var price = pPrice;
var myObj = {
id:{
'name':name,
'price':price
},
};
(id++); //
console.log(myObj.id.name); // Acessing specific data
}
I want my id field to be defined by the id variable value so it would create a new field each time my function is called. But I don't find any solution to concatenate both.
Thanks
You can create and access dynamicly named fields using the square bracket syntax:
var myObj = {};
myObj['id_'+id] = {
'name':name,
'price':price
}
Is this what you want ?
var myObj = {};
myObj[id] = {
'name':name,
'price':price
};
console.log(myObj[id]name); // Acessing specific data
You can use [] to define the dynamic property for particular object(myObj), something like
var myObj = {};
myObj[id] = {'nom':nom, 'prix':prix};
Example
function userDetail(id, nom, prix) {
var myObj = {};
myObj[id] = {'nom':nom, 'prix':prix};
return myObj;
}
var objA = userDetail('id1', 'sam', 2000);
var objB = userDetail('id2', 'ram', 12000);
var objC = userDetail('id3', 'honk', 22000);
console.log(objA.id1.nom); // prints sam
console.log(objB.id2.nom); // prints ram
console.log(objC.id3.prix);// prints 22000
[DEMO]
I have a table that have a property named "recordsource" that will hold the name of the object that will fill the content of the table.
<table id="tbl" recordsource="myobj">
Now here are my functions:
var myobj;
function obj()
{
this.code = new Array();
this.name = new Array();
}
myobj = new obj();
myobj.code = ["a","b","c"];
myobj.name = ["apple","banana","carrot"];
function populate_table()
{
mytable = document.getElementById("tbl");
mytableobj = mytable.getAttribute("recordsource"); //this will return a string
//my problem is how to reference the recordsource to the myobj object that have
//the a,b,c array
}
try this window[ mytableobj ] it will return myobj
One way is to use an object as a list of all the other objects that you want to be able to access.
...
var obj_list = {
'myobj': myobj
};
function populate_table()
{
mytable = document.getElementById("tbl");
mytableobj = mytable.getAttribute("recordsource");
// Then obj_list[mytableobj] == myobj
obj_list[mytableobj].code[0] // Gives "a"
obj_list[mytableobj].name[0] // Gives "apple"
}
It's a silly question, but is this an array of objects in js?
var test =
{
Name: "John",
City: "Chicago",
Married: false
}
if so, how do I declare a new one.. I dont think
var test = new Object();
or
var test = {};
is the same as my example above.
No.
That's an object with three properties.
The object literal is just a shortcut for creating an empty object and assigning properties:
var test = { }; //or new Object()
test.name = "John";
test.city = "Chicago"
test.married = false;
An array of objects would be
myArray = [
{ prop1 : "val1", prop2 : "val2" },
{ prop1 : "A value", prop2 : "Another value" }
]
You would access the first object's prop2 property like this
myArray[0].prop2
"if so, how do I declare a new one?"
To do what I think you want you would have to create an object like this
var test = function() {
this.name = "John";
this.city = "Chicago";
this.married = false;
}
var test2 = new test();
You could alter the properties like this
test2.name = "Steve";
You can create an array of your objects like this
myArray = [test, test2];
myArray[1].married = true;
No, it's an object.
You could create an array of objects like this:
var array_of_objects = [{}, {}, {}];
For creating new objects or arrays I would recommend this syntax:
var myArray = [];
var myObject = {};
No, test is an object. You can refer to it's instance variables like so:
var myname = test.Name;
It is an object, but you must also understand that arrays are also objects in javascript. You can instantiate a new array via my_arr = new Array(); or my_arr = []; just as you can instantiate an empty object via my_obj = new Object(); or my_obj = {};.
Example:
var test = [];
test['name'] = 'John';
test['city'] = 'Chicago';
test['married'] = false;
test.push('foobar');
alert(test.city); // Chicago
alert(test[0]); // foobar