Define two objects with the same name in javascript - javascript

Is it possible to define two objects with the same name in javascript..
for example
var record = {
id: some value,
name: some value,
subject: some value,
};
and again
var record = {};

No and Yes
No if is global variable or you insert in the same group example:
if(){
var record = {
id: some value,
name: some value,
subject: some value,
};
var record = {};
}
Yes If you make local variable or insert in diferent groups like:
if(){
var record = {
id: some value,
name: some value,
subject: some value,
};
} else {
var record = {};
}

In JavaScript, a variable can be declared after it has been used.
In other words; a variable can be used before it has been declared.
You can declare a uniquie variable only in a scope. you must read java-script hoisting:
http://www.w3schools.com/js/js_hoisting.asp

Related

Is there a way to force a javascript element to redefine itself based on how it was originally defined?

I was playing around with objects and constructors and stuff like that, and I was wondering if there was a way to bind a value to a variable based on how it was originally defined. I have the following code:
typescript
let cr = "create",
ap = "apply",
$this = {
set: (prop, value) => {
this[prop] = value;
}
};
function creator() {
this.$ = (array: Object[]) => {
array.forEach((kp: Object) => {
let key = Object.keys(kp)[0];
let val = kp[Object.keys(kp)];
$this[key] = val;
creator.create(key, { value: val });
});
};
this.apply = (...objects: Object[]) => {
objects.forEach((obj: Object) => {
creator.call(obj);
});
};
}
function create(obj) {
function createValues(arr) {
let instance: Object = new obj();
let vals: any[] = [];
arr.forEach(name => {
vals.push(instance[name]);
});
return vals;
}
let names: string[] = Object.getOwnPropertyNames(new obj());
let values: string[] = createValues(names);
return combineArrays(names, values);
}
function combineArrays(arr1, arr2): { $?: any } { // the question mark removes an IDE error
let newObj: Object = {};
arr1.forEach(prop => {
newObj[prop] = arr2[arr1.indexOf(prop)];
});
return newObj;
}
Object.prototype.create = function(prop, options) {
return Object.defineProperty(this, prop, options);
};
create(creator).$([
{ hi: "hi" },
{ bye: $this["hi"] } // this is the important stuff
]);
I was wondering if there is a way, inside the set function of the $this variable, to detect how it is being set and therefore determine if that value has changed and so it's value should to, if that makes any sense? Let's say you had this:
let $this = {
set: function(prop, value) {
this[prop] = value;
}
}
let name = 'Ezra';
$this['name'] = name;
// then :
name = 'Bob';
// change $this.name too, so then:
console.log($this.name);
// >> 'Bob'
I believe this is called Data-Binding but I am unsure how to do it without creating endless numbers of proxies.
What you're describing is not really "data-binding" but pass-by-reference. In your example you expect an update to name to be reflected in $this['name']. That would only be possible if you were passing a reference (or a pointer) to the variable.
However, in this case the variable is a string, and strings in JavaScript are immutable:
no string methods change the string they operate on, they all return new strings. The reason is that strings are immutable – they cannot change, we can only ever make new strings.
So, going step-by-step through your example:
This creates a new string named 'Ezra', and assigns a variable called name to reference that string.
let name = 'Ezra';
This creates (or sets) a property in $this called 'name' that references the string in name (which is 'Ezra').
$this['name'] = name;
This creates a new string called 'Bob' and stores it in the variable called name. The variable already exists. This does not mutate the value that was previously held in there. Instead, name is being updated to point to a new reference.
// then :
name = 'Bob';
However, if you were to pass an object, you'll notice that you can actually mutate it. This is because objects are passed-by-reference and you can mutate the value at that reference.
For example:
// Create a new value that stores an object, with a property 'firstName'
let name = { firstName: 'Ezra' };
// Assign myObject to $this['name']. Now $this['name'] and name both point to the same reference.
$this['name'] = name;
// Change the value in the object pointed-to by name
name.firstName = 'Bob'
console.log($this['name'].firstName); // <- This will output 'Bob'

Javascript - get object value using variable

I'm trying to get an object value by passing a variable to a function, but I'm not sure how to do this with a multi layer object. It looks like this:
var obj = {
field1: { name: "first" },
field2: { name: "second" }
};
var test = function(field){
//sorting function using obj[field]
//return results
};
With the above, the following works:
var result = test("field1");
This sorts using the object {name: "first"} but say I want to use just the name value. I can't do this:
var result = test("field1.name");
What is the correct way to do this?
what about this?
var result = test("field1", "name");
var test = function(field, keyname){
return obj[field][keyname];
};

Separating truthy and falsey values from an object

I'm working on a java challenge that reads
//In the function below you'll be passed a user object. Loop through the user object checking to make sure that each value is truthy. If it's not truthy, remove it from the object. Then return the object. hint: 'delete'.
function truthyObjLoop(user) {
//code here
I came up with....
var user = {};
user.name = {};
user.age = {};
if (user !== false)
{
return user;
} else {
delete user;
}
}
However whenever I try it it comes back with the error Function returned
{"name":{},"age":{}}
instead of
{"name":"ernest","age":50}
when passed
{"name":"ernest","age":50,"funky":false}....
Can anyone help me understand why this is happening or if I'm using the wrong symbols here? Thank you.
var user = {};
user.name = {};
user.age = {};
The user name and age should be the values, not Objects. curly braces mentions objects, you are wrong.try my following code please
var user = {};
user.name = "john";
user.age = 12;
Also read this tutorial please :
http://www.w3schools.com/json/
The text says "you'll be passed a user object". That means the user is being defined outside of the function, and passed in. Here's what you're looking for:
function truthyObjLoop(user) {
for (var k in user) {
if (!user[k]) delete user[k]
}
console.log(user);
}
You then should pass in a "user" with all sorts of different attributes to demonstrate how the test works:
var person = {
age: 29,
gender: "male",
pets: [
{
type: "cat",
name: "smelly"
}
],
children: 0,
married: false
};
truthyObjLoop(person);
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/tb823pyp/
Notice it removes the attributes with a value of 'false' or '0'.

Javascript - Using an array as a parameter to a function and changing values when creating new prototype object

I have a constructor where name is a string and details should be an array containing animal type, age and colour.:
function animal(name, details) {
this.animal_name = name;
this.animal_details = details;
}
I want to create a new object from this prototype:
var myPet = new animal("Olly", " /* what goes here? */ ");
How do I declare the array in this case (is it like the usual array declaration) How do I use this when creating a new object myPet?
NB: This is my previous way of doing this without using an array:
function meal (starter, main, side, dessert, drink) {
this.starter = starter;
this.main = main;
this.side = side;
this.dessert = dessert;
this.drink = drink;
}
var myMeal = new meal("soup", "chicken", "garlic bread", "cake", "lemonade");
Arrays can be declared inline using square brackets:
var a = [1, 2, 3];
In your case, you can use this directly in your call to new animal:
var myPet = new animal("Olly", ["dog", 3, "brown"]);
An alternative approach, which if you want to store all the details together in this way is the one I'd take, is to pass in an object:
var myPet = new animal("Olly", {type: "dog", age: 3, colour: "brown"});
This means you can then access the details by name:
console.log(myPet.animal_details.type); //dog
You can declare an array like this:
var myPet = new animal("Olly", ['cat','white','big']);
//myPet.animal_details[0] === 'cat';
but I think an object will fit better with your solution
var myPet = new animal("Olly", {type: 'cat',color: 'white', size: 'big'});
//myPet.animal_details.type === 'cat';
//myPet.animal_details.color === 'white';
//myPet.animal_details.size === 'big';
You may find it easier to use object instead of an array because it would be easier to define default properties if they are not present. An object's structure is a little better for handling this type of data too, imo:
function Animal(details) {
this.name = details.name || 'Dave';
this.age = details.age || 10;
this.location = details.location || 'Dorset';
}
var cat = new Animal({ name: 'Simon', location: 'London' });
// Object { name: "Simon", age: 10, location: "London" }
PS. Always captitalise your constructor names.
Of course, if you're not worried about default values and just want the items specified in your object to be added to the instance, this is a simple method to use:
function Animal(details) {
for (var p in details) {
this[p] = details[p];
}
}
var cat = new Animal({ name: 'Simon', location: 'London' });
// Object { name: "Simon", location: "London" }
You can use this approach, to dynamically add details for every instance:
//Base Animal Class
function Animal(name,options) {
//Localise Class Variable
var me = this;
//Assign name to class variable
me.name = name;
//Assign details dynamically, depends on every instance
for(var index in options) {
me[index] = options[index];
}
}
//Create Animal Instance
var PetInstance = new Animal("Max",{
age:11,
kind:"Pudel"
});
console.log(PetInstance);
//Create Another Animal With Different Details
var PetInstance2 = new Animal("Foo",{
age:22,
kind:"Doberman"
});
console.log(PetInstance2);
See this JSFiddle Example:
http://jsfiddle.net/shako92/bretpu5c/
You could use instant-array notation: ['Furry', 'Sharp nails', 'Black']. Although you might wanna go with an object so you aren't depending on "which index did I use to put the skin-type?" So something like:
{
'skin':'Furry',
'paw':'Sharp nails',
'color':'Black'
}
(If this looks like JSON to you, it's because it is, JSON = JavaScript Object Notation)
Alternatively, you could leverage the built-in arguments array to extract (part of) the arguments given as an array and assign it:
function animal(name) {
this.animal_name = name;
this.animal_details = arguments.slice(1); // get a "slice" of the arguments array starting at index 1 (skipping the name argument)
}
var myPet = new animal("Olly", 'Furry', 'Sharp nails', 'Black');
you should try use the 'arguments' var inside your function, like this:
function a (){
for(arg in arguments){
console.log(arg);
}
}
a(1,2,3,4,5,6,7);
The result will be:
1
2
3 [...]
This way you let your code simple and useful.

Create a new unique global variable each time a function is run in javascript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript dynamic variable name
A very basic question. I want to create a new javascript global variable each time a function is called. The variable should contain the id of the element so that I can easily access it later.
id = 2347
//this function would be called multiple times, hopefully generating a new global each time
function (id)
{
var + id = something
// I want a variable that would be named var2347 that equals something, but the above line doesn't get it.
}
In a later function, I want to access the variable like so:
function two (id)
{
alert(var + id);
}
I'm sure I'm going to have a "doh!" moment when someone is kind enough to answer this.
How about...
var store = (function() {
var map = {};
return {
set: function ( name, value ) {
map[ name ] = value;
},
get: function ( name ) {
return map[ name ];
}
};
})();
Usage:
store.set( 123, 'some value' );
and then...
store.get( 123 ) // 'some value'
store.get( 456 ) // undefined
Live demo: http://jsfiddle.net/jZfft/
Programmers are highly advised to not declare global variables, since the browsers already ship with several hundreds of names in the global namespace. Using the global namespace for your own variables can lead to name-collisions which can then break the program or some of the browser's functionality. Creating new namespaces is free, so don't be shy to do it...
Global variables are properties of the window object, so window.lol and window['lol'] define a global variable lol which can be accessed in any of these ways.
The second, window['lol'], can also be used with variable names, like this:
var lol = 123;
var name = 'lol';
var content = window[name]; // window['lol'] == 123
content will now contain 123.
Pretty much anything can be put between square brackets [], so you can also do this:
var id = 123;
window['prefix' + id] = 'text';
var content = window['prefix' + id]; // prefix123 == text
Or, in your case:
var id = 2347;
function one(id) {
window['var' + id] = something;
}
function two(id) {
alert(window['var' + id]);
}
You can save your values to the global hash:
var g = {};
function (id)
{
g[id] = something;
}
function two (id)
{
alert(g[id]);
}
I would argue that you don't really want to be making lots of global variables. Rather, you can just make one global object or array and attach all your other variables to that. In this case, you probably want an object:
var myIds = {};
function makeSomething(id) {
// create something that goes with this id
myIds[id] = something;
}
Then, to fetch that information at some time later, you can retrieve it with this:
var something = myIds[id];
The reason for this suggestion is many-fold. First off, you want to minimize the number of global variables because every global is a chance for a naming collision with some other script you might be using. Second off, when keeping track of a bunch of related data, it's a better programming practice to keep it in one specific data structure rather than just throw it all in the giant global bin with all other data.
It's even possible to create an object that manages all this for you:
function idFactory() {
this.ids = {};
}
idFactory.prototype = {
makeSomething: function(id) {
// create something that goes with this id
this.ids[id] = something;
},
retrieveSomething: function(id) {
return(this.ids[id]);
},
clear: function() {
this.ids = {};
}
};
// then you would use it like this:
var myIds = new idFactory();
myIds.makeSomething(2347);
var value = myIds.retrieveSomething(2347);

Categories

Resources