Say, I have 2 constructors assigned to 2 variables:
var example1 = function(argument1){
this.argument1 = argument1;
}
var example2 = function(argument2){
this.argument2 = argument2;
}
And an array of objects containing objects from both of these constructors:
var array1 = new Array();
array1[0] = new example1(example);
array1[1] = new example2(example);
My question is, when I choose an item from the array, how can I print the name of the constructor variable it came from?
To make this clear and succint, here's an example:
console.log(array1[0].argument1)
Will print example. But I don't want that. I want it to print the name of the constructor variable it came from.
console.log(array1[0].constructor.toString());
Prints the content of the variable, but it is unsatisfactory.
You need to provide a name to a function:-
var example1 = function example1(argument1){
this.argument1 = argument1;
}
var array1 = new Array();
array1[0] = new example1({});
console.log(array1[0].constructor.name)
in most browsers, functions have a name, but you don't use it.
so, we have to resort to hacks to find your constructor in the cloud, which won't work in IE7, maybe 8:
console.log(Object.keys(self).filter(function(a){
return self[a]===array1[0].constructor;
})[0]);
if you didn't have the code running in the global scope, this trick won't work!
again, this is a hack and you should find a better way of doing things, like naming your functions, even if they are expressions.
Try instance of,
var example1 = function(argument1){
this.argument1 = argument1;
}
var example2 = function(argument2){
this.argument2 = argument2;
}
console.log(getName(array1[0]));
function getName(value) {
if (value instanceof example1) return 'example1';
if (value instanceof example2) return 'example2';
return '';
}
Related
I have a constructor object in my code which is:
function Employee(){
this.name = names[Math.floor(Math.random() * names.length)];
this.age=1;
this.level=1;
this.production=400;
this.totalprod=0;
}
So when I create a new Employee I just say:
var employee1 = new Employee();
So then I can manipulate this instance of the object. Now, I want this objects to be created dynamically with the variable names: employee1, employee2, employee3 and so on.. Is there a way to achieve this or is it impossible?
And the other question that I have, say that I want to change the age of all instances at the same time, is there a way to do this? Thanks in advance and sorry if the question in silly, I'm learning!
EDIT: This is not the same as the other question as I'm using a constructor Object, not a literal Object, and, apart from that, I ask another question which is how to change a property of all instances at the same time, thanks!
This isn't really possible without the use of something like eval, which is bad practice.
Instead if you knew how many employees you wanted to make in advance you could do something like this.
Example: https://jsfiddle.net/dbyw7p9x/
function makeEmployees(n) {
var employees = new Array(n)
for (var i = 0; i < n; ++i) {
employees[i] = new Employee()
}
return employees
}
alternatively you could make also make it return an object which interestingly, while not exactly the same as the array, would be accessed in the same way as an array using numbers inside square brackets obj[0], obj[1], obj[2], obj[3] etc.
function makeEmployeesObj(n) {
var employees = {}
for (var i = 0; i < n; ++i) {
employees[i] = new Employee()
}
return employees
}
To change a property for each approach you can do:
// Array
for (var i = 0; i < e1.length; ++i) {
e1[i].age = 2
}
// Object
Object.keys(e2).forEach(function(key) {
e2[key].age = 2
})
Here is one way to do it, using an array, we push to new Employees to it, and return that array:
To add a specific value, in this case age, I recommend passing it in as a parameter to your Employee constructor, you can do this with all of the this parameters if you like:
Notice in the JsBin that all the ages are different, they are actually the value of n:
Working example: JSBin
function Employee(age){
this.name = 'something';
this.age= age;
this.level=1;
this.production=400;
this.totalprod=0;
}
function maker(n) {
var arr = [];
while (n > 0) {
arr.push(new Employee(n));
n--;
}
return arr;
}
I was going through the WURFL.js source, I saw this towards the bottom of the page:
var logo=document.getElementById("hero"),heroText=document.getElementById("hero"), ...
Obviously, the variables, logo and heroText, are referring to the same thing. Isn't that an unnecessary overhead on the DOM parsing in JavaScript (since JavaScript has to look for the id hero each time)? Apparently, a more efficient one is:
var logo=document.getElementById("hero");
var heroText = logo;
In that case, heroText could be another object or could also be referring to the same object as logo. I don't know which because I don't know how the JavaScript interpreter works (I'm a C# person, a learner, though).
So my question is really this: (I'm assuming WURFL didn't make a mistake) how does JavaScript interpret the two lines? Thanks, in advance.
The difference would be (if it weren't returning a DOM element) that if you do
var getObj = function() { return {} };
var a = getObj();
var b = getObj();
a.test = 'hi';
console.log(b);
// Object {}
But if you do:
var getObj = function() { return {} };
var a = getObj();
var b = a;
a.test = 'hi';
console.log(b);
// Object {test: "hi"}
One results in two unique objects, the other in two references to the same object.
var a = document.getElementById('notify-container')
var b = document.getElementById('notify-container')
a.test = 'hi'
console.log(b.test);
//"hi"
So, in the instance you are showing, yes it is more efficient to do
var logo=document.getElementById("hero");
var heroText = logo;
There clearly seams to be a mistake. Because document.getElementById returns a 'live' representation of a node. That means that whenever that element changes, the variable that holds tha node ( logo, heroText ) is also changed; also, if you check those two variables for equality they will be the same.
How would I create dynamic variable names in NodeJS? Some examples say to store in the window variable, but I was assuming that is client-side Javascript. Correct me if I'm wrong.
Generally you would do something like:
var myVariables = {};
var variableName = 'foo';
myVariables[variableName] = 42;
myVariables.foo // = 42
In node.js there is the global context, which is the equivalent of the window context in client-side js. Declaring a variable outside of any closure/function/module as you would in plain Javascript will make it reside in the global context, that is, as a property of global.
I understand from your question that you want something akin to the following:
var something = 42;
var varname = "something";
console.log(window[varname]);
This in node.js would become:
var something = 42;
var varname = "something";
console.log(global[varname]);
Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
One possible solution may be:
Using REST parameter, one can create an array and add each dynamic variable (REST parameter item) as an object to that array.
// function for handling a dynamic list of variables using REST parameters
const dynamicVars = (...theArgs) => {
let tempDynamicVars = [];
// as long as there are arguments, a new object is added to the array dynamicVars, creating a dynamic object list of variables
for (let args = 0; args < theArgs.length; args++){
const vName = `v${args}`;
tempDynamicVars = [...tempDynamicVars, {[vName]: theArgs[args]}]; //using spread operator
// dynamicVars.push({[vName]: theArgs[args]}); // or using push - same output
}
return tempDynamicVars;
}
// short version from above
// const dynamicVars = (...theArgs) => theArgs.map((e, i) => ({[`v${i}`]: e}));
// checking
const first = dynamicVars("F", 321);
console.log("Dynamic variable array:", first);
console.log(` - ${first.length} dynamic variables`);
console.log(" - second variable in the list is:", first[1], "\n");
console.log(dynamicVars("x, y, z"));
console.log(dynamicVars(1, 2, 3));
console.log(dynamicVars("a", "b", "c", "d"));
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I store reference to a variable within an array?
Consider the following code:
var a = 'cat';
var b = 'elephant';
var myArray = [a,b];
a = 'bear';
myArray[0] will still return 'cat'. Is there a way to store references in the array instead of clones, so that myArray[0] will return 'bear'?
While I agree with everyone else saying that you should just use myArray[0] = whatever, if you really want to accomplish what you're trying to accomplish you could make sure that all you variables in the array are objects.
var a = {animal: 'cat'},
b = {animal: 'elephant'};
var myArray = [a, b];
a.animal = 'bear';
myArray[0].animal is now 'bear'.
No. JavaScript doesn't do references in that way.
Nope, it is not possible. JavaScript doesn't support such references.
Only objects are stored as references. But I doubt it's what you want here.
You've kind of answered your own question. If you want myArray[0] to equal bear, then set:
myArray[0] = "bear";
Even if your array holds references to objects, making a variable refer to an entirely different object would not change the contents of the array.
Your code does not modify the object variable a refers to. It makes variable a refer to a different object altogether.
Just like your JavaScript code, the following Java code won't work because, like JavaScript, Java passes references to objects by value:
Integer intOne = new Integer(1);
Integer intTwo = new Integer(2);
Integer[] intArray = new Integer[2];
intArray[0] = intOne;
intArray[1] = intTwo;
/* Make intTwo refer to a completely new object */
intTwo = new Integer(45);
System.out.println(intArray[1]);
/* output = 2 */
In Java, if you change the object referenced by a variable (instead of assigning a new reference to a variable) you get the behavior you desire.
Example:
Thing thingOne = new Thing("funky");
Thing thingTwo = new Thing("junky");
Thing[] thingArray = new Thing [2];
thingArray[0] = thingOne;
thingArray[1] = thingTwo;
/* Modify the object referenced by thingTwo */
thingTwo.setName("Yippee");
System.out.println(thingArray[1].getName());
/* output = Yippee */
class Thing
{
public Thing(String n) { name = n; }
private String name;
public String getName() { return name; }
public void setName(String s) { name = s; }
}
What is the differnce between following two?
obj = new Object();
OR
obj = {};
In my code am asked to replace first notation with second one and the code is huge.Will replacing it cause any problem?
According to JavaScript Patterns book, using a built-in constructor (obj = new Object();) is an anti pattern for several reasons:
it's longer to type than literal (obj = {};)
literal is preferred because it emphasizes that objects are mutable hashes
scope resolution - possibility that you have created your own (local) constructor with the same name (interpreter needs to look up the scope chain)
I will answer the second question:
Will replacing it cause any problem?
Nope, it won't cause any problem.
If you have for example those lines:
var obj = new Object("a");
//...code...
obj = new Object("b");
//...code...
Changing to this will have same result and no impacts:
var obj = { "a": 1 };
//...code...
obj = { "b": 2 };
//...code...
By assigning the variable with the = you're overwriting whatever it contained with the new value.
There is no difference. The former uses the Object constructor, whereas the latter is a literal, but there will be no difference in the resulting objects.
Greetings
Objects in JavaScript
1- var obj = { key1 : value1 , key2Asfunction : funciton1(){} };
obj.key1;
obj.key2Asfunction();
2- var obj = function()
{
this.obj1 = value1 ;
this.function1 = function(){};
}
var ob = new obj();
ob.obj1;
ob.function1();
if you need how to create the structure of the jquery frame work too i can help
Regrads :)