Parameter name in object when its created - javascript

I want to get parameter name when a function applied as new. I have search but i couldn't find what i am exactly looking.
Here is a sample;
var myobject = function(){
/*I need "param" in here as string*/
}
var param = new myobject();
thanks for any idea or referance without any library.
the original case code is:
var selectQueue = [];
var queue = function(data){
this.defaults = {
name: "base",
type: "fifo"
}
this.availableTypes = ["fifo","lifo","random"];
if(!data){data = {};}
for(param in this.defaults){
if(!data[param]){
data[param] = this.defaults[param];
}
}
/*this is what i want to do with dynamic name*/
selectQueue.push({
a:this
});
}
var a = new queue();

What you want is not really possible in JS, but a possible workaround is to send the name you want to the constructor, such as:
var selectQueue = [];
var queue = function(data, name){
this.defaults = {
name: "base",
type: "fifo"
}
this.availableTypes = ["fifo","lifo","random"];
if(!data){data = {};}
for(param in this.defaults){
if(!data[param]){
data[param] = this.defaults[param];
}
}
var o = {};
o[name] = this;
selectQueue.push(o);
}
var a = new queue(data, 'a');
Another possibility is to keep track of the current index of selectQueue.

The object has properties and this is the syntax.
var myObject = function(){
name: "your name",
age: 19,
hobby: "football"
}
var param = myObject.name;
That is the way you define a property.

Related

how to right choose javascript pattern

i create 2 objects:
var Documentos = new QuadForm();
var Cadastro = new QuadForm();
And initialize this objects with lot of options
Cadastro.initForm(options);
Documentos.initForm(options2);
then i try to separate the data managed by each object with getName method but after the second object, myObjectName variable is overrided.
var QuadForm;
QuadForm = function () {
this.getName = function () {
// search through the global object for a name that resolves to this object
for (var name in window)
if (window[name] == this) {
window[name] = this;
window[window[name]] = window[name];
myObjectName= name;
break;
}
},
this.initForm = function (parms) {
this.getName()
$.extend(this, parms);
if (window.myState) {
delete window.myState;
}
this.containerId = parms.formId;
this.getForm(parms);
this.workflowLabels('hide');
then i use window[myObjectName].totalRecords but as it changes to the latest object name off course cannot access data.
How can i manage this.
It's not a big problem to manage several instances, but your approach is impossible, cause you can't really find all possible instances and your code does definitely not what you expected to do.
For example you can define a variable on the constructor-object which holds all instances, and than you can use it in some cases:
var QuadForm = function (name) {
this.name = name;
QuadForm.instances.push(this);
this.showAllOtherInstances = function () {
QuadForm.instances.forEach(function (instance) {
if (instance !== this) {
console.log('name: ' + instance.name);
}
}.bind(this));
}
}
QuadForm.instances = [];
var foo = new QuadForm('foo');
var anotherFoo = new QuadForm('foo');
var bar = new QuadForm('bar');
var aThirdFoo = new QuadForm('foo');
foo.showAllOtherInstances();
/*
* Output:
*
* name: foo
* name: bar
* name: foo
*/

Real use case dynamic (computed) property

A dynamic property:
var obj = {
// Computed (dynamic) property names
[ 'prop_' + (() => 42)() ]: 42
};
This is of course very fancy. But where could someone use this without adding unnecessary complexity?
If you have a property name as a constant:
var obj = { [SOME_CONSTANT]: 42 };
One case where I wanted it was where property names for JSON were defined in generated files, based off Java classes.
// Generated
var SomeJsonBodyParams = {NAME: 'name', ID: 'id', ETA, 'estimatedTimeOfArrival'};
// Using it
sendAjax('some/url', {
[SomeJsonBodyParams.NAME] = userData.name,
...
});
We even had a method so we could kind of do it
function makeObj() {
var obj = {};
for (var i=0; i < arguments.length; i+=2) {
obj[i] = obj[i+i];
}
return obj;
}
sendAjax('some/url', makeObj(
SomeJsonBodyParams.NAME, userData.name,
...
));
You can use it in class and with Symbols:
class MyClass {
[Symbol.iterator]() {
// my iterator
}
}
Let's say you have:
var hi = 'hi';
var test = 'test';
var hello = 'hello';
Instead of:
var object = {};
object[hi] = 111;
object[test] = 222;
object[hello] = 333;
You could write it in a much shorter syntax:
var object = {
[hi]: 111,
[test]: 222,
[hello]: 333
}
E.g. it could be used when you want to use a, let's say, constant as a key in object.
const DATA_TYPE = {
PERSON: 'person',
COMPANY: 'company'
};
let cache = {
[DATA_TYPE.PERSON]: getPerson()
};
And later access:
cache[DATA_TYPE.PERSON]
Instead of DATA_TYPE.PERSON could be anything (including some real-time calculated values).

Adding protos but keeping object structure, javascript

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');

Concatenate object field with variable in javascript

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]

How to make a class/object that can be referenced at multiple levels

I have read many, many ways of making makeshift classes in javascript. I'm trying to create a giant list of items, each with a variety of variables. I need to be able to call a certain object's properties from this list.
The following code compiles, but when line 9 tries to access items.yspeed1.name, it creates the button with the name "undefined". I have no clue how to access a function's variables in javascript like this.
var itemslist = function(){
this.yspeed1 = function(){
this.name = 'Yellow Upgrade';
this.price = 50;
}
this.yspeed2 = function(){
this.name = 'Blue Upgrade';
this.price = 25;
}
}
var newitem = document.createElement('button');
newitem.innerHTML = items.yspeed1.name;
shop.appendChild(newitem);
Well, for a starters yspeed1 is a function so you have to call it anyway, I think this might be the sort of thing you're looking for.
var itemslist = function(){
this.yspeed1 = {
name: 'Yellow Upgrade',
price: 50
}
}
This is just one way. other than that you'll have to create a
new items.yspeed1();
You use a class in JS when you are defining a reusable structure with state, i.e. you might have multiple copies (instances) of a class.
What you have is just a definition of a single object (single instance) with properties. So use that Javascript construct instead:
var itemslist = {
yspeed1: {
name: 'Yellow Upgrade'
, price: 50
}
, yspeed2: {
name: 'Blue Upgrade'
, price: 25
}
}
Now you have a single object with two properties -- yspeed1 and yspeed2. And those each have their own properties of name and price.
If you want to expand that object, just add to it, e.g. itemslist.yspeed3 = { hello: 'world' };
There are situations where "classes" are useful, but I think you can get away with a simple object here.
var items = {}
items.yspeed1 = {}
items.yspeed1.name = 'Yellow Upgrade';
items.yspeed1.price = 50;
items.yspeed2 = {};
items.yspeed2.name = 'Blue Upgrade';
items.yspeed2.price = 25;
var newitem = document.createElement('button');
newitem.innerHTML = items.yspeed1.name;
shop.appendChild(newitem);
if your looking to use a class based approach here's one using prototypes
Item Class:
function YSpeedItem(name, price)
{
this.name = name;
this.price = price;
}
YSpeedItem.prototype.getName = function()
{
return this.name;
}
YSpeedItem.prototype.getPrice = function()
{
return this.price;
}`
main code
var yspeed1 = new YSpeedItem("Yellow Upgrade", 50);
var yspeed2 = new YSpeedItem("Blue Upgrade", 25);
itemsList = [];
itemsList.push(yspeed1);
itemsList.push(yspeed2);
var newitem = document.createElement('button');
newitem.innerHTML = items[0].getName;
shop.appendChild(newitem);
more info here http://www.phpied.com/3-ways-to-define-a-javascript-class/

Categories

Resources