How to name an anonymous Object in Javascript? - javascript

I have part of my code which creates several instances of a Player class by the following code:
player.push(new Player(i, positions[randomPosPlayer]));
Hence I'm not using the conventional way i.e. var somePlayer = new Player(x,y);
Assuming 3 players are created, all of them appear as anonymous Objects. How can I name them while maintaining the key-value of each Object?

I don't know if you are using custructor functions or the es6 class syntax but either way you can "name" your players in it's constructor by something like this:
let allPlayers = {};
function Player(x,y,name){
if(name)allPlayers[name] = this;
//...other constructor stuff
}
and just pass the name when you create it:
player.push(new Player(i, positions[randomPosPlayer],"CustomName"));
and then you can simply get the players by name using
let p = allPlayers["CustomName"];
or even by accessing the attribute directly if you are sure a player with this name exists:
let p = allPlayers.CustomName;

Related

Inconsistency with bracket notation in object property accessors for dynamically named constructor-function. Is there an explanation?

I want to dynamically create objects of dynamically named class (sorry JS, I got used to call them classes) via dynamically named anonymous function. In this answer I found out that...
As of ES2015, the function created by an anonymous function expression
assigned to an object property takes the name of that object property.
So I tried this code:
// dynamically named constructor function
this['Item'] = function(size) {
this.size = size;
}
// the creation of new object of arbitrary name
let item = new this['Item']('small')
console.log(item);
console.log(this['Item'].name)
and it works:
BUT when I am actually using the variable name...
let clsName = 'Item';
// dynamically named constructor function
this[clsName] = function(size) {
this.size = size;
}
// the creation of new object of arbitrary name
let item = new this[clsName]('small')
console.log(item);
console.log(this[clsName].name)
It is acting weird:
The task itself is much less of an issue for me then the fact that behavior of obj['string'] and obj[variableWithString] differs. So can anybody please explain this phenomena for me? Shouldn't the result in the second example be the same that was in the first one?

I need an idea of creating methods that take elements before it

I need an idea of creating methods that take elements before it
note it should take a defined element instead of an object
example:
"use strict";
var element = document.getElementById('name').value;
elment.capitalize();//the capitaze should be a function
i will appriciate for your help.
No you cannot use the method to get associated with a variable and invoke that. For that scenario we have objects to take care of. You can create a object data structure with necessary properties and functions so that when you call capitalize() function of that object you get the uppercase value of name property of that object.
var element = {
name: 'name',
capitalize: function(){
this.name = this.name.toUpperCase();
return this.name;
}
}
var name = element.capitalize();
console.log(name);

Two different ways to make javascript objects

I am new to Javascript and now studying it...
var person = function() {
this.name = "name"
};
var person2 = function() {
var obj = {};
obj.name = "name";
return obj;
};
Let's suppose we have two functions shown above. It seems that objects can be created by using either of the functions. For example)
var p = new person();
var p2 = new person2();
My question is: What's difference between person vs person2? Are they exactly the same? If not which one is a more preferable way to use?
Thanks
The normal way of creating an object is the first way.
The second way will create two objects, and one will be discarded. One object will be created before the function is called, just as with the first method, but because the function returns another object the first object will be discarded and the returned object will be used instead.
An important difference between the methods is that the second one can't use a prototype. Anything that you put in the prototype of the function will be applied to the object that ends up being discarded.
The difference is in the way you use the functions.
The first one is intended to be used as a constructor, this being set to the newly created object. It is intended to be used in combination with the operator new, as follows:
var bill = new person();
This is just like a normal constructor as in typical OOP language.
The second one is intended to be used as a normal function (without new), e.g.:
var bill = person();
You can use this way of object creation in combination with the builder pattern.

Trouble with Objects

Basically i'm having trouble with something that i'm sure is super duper simple but I just don't know what to call it and therefore I am having trouble searching for an answer. :(
Basically, say I've declared an object, i.e var meow = {}; and then i decide to create an object within that by doing something like meow.cutekitten = {}; this is all straight forward and i end up with an object called cutekitten within that.
My issue is, what if I've declared cutekitten as a variable and i want to use the contents of that variable as the name of this new object rather than the variable name?
var propertyName = "cutekitten";
var meow = {};
meow[ propertyName ] = {};

Javascript: How to get the right instance of an object from an event handler when their are multiple instances of the object

I created an object and it works great when I have one instance of the object. This isn't the actual Object, but the concept is the same.
function foo(name){
this.name = name;
}
foo.prototype.CreateElement = function(){
var newElement = document.createElement("a");
that = this;
newElement.onclick = function(){
that.SayName(this);
};
document.getElementsByName("body")[0].appendChild(newElement);
}
foo.prototype.SayName = function(LinkObj){
alert(this.name);
LinkObj.href = "http://google.com";
}
I was told that by saving the instance of this to a variable (in this case that), I would still get a reference to the correct object instance for the SayName method. This would leave this to represent the instance of the element passed in from the onclick. This all seems to work properly with only one instance, but when I create multiple instances of the object I end up with the last instance being the instance supplied in the onclick event.
I initialize two objects like this
var ObjOne = new foo("Ted");
ObjOne.CreateElement();
var ObjTwo = new foo("Steve");
ObjTwo.CreateElement();
and when the onclick fires for ObjOne, I get the object instance for ObjTwo and so this.Name is set to Steve.
Does anyone know how I can get the right object instance when the onclick event fires from various instances? I assume i need to bind the correct instance with call, but i'm not really sure how to.
Thanks in advance and hope this wasn't to confusing.
The problem is this line:
that = this;
You declared that without using var, which means it is global, i.e., all your instances are updating the same global that variable. Do this instead:
var that = this;
Then that will be local to each. (That is, local to each closure of the CreateElement function.)
Demo: http://jsfiddle.net/SEsLJ/
Also, document.getElementsByName should be document.getElementsByTagName (assuming you didn't actually give the body a name attribute equal to "body").

Categories

Resources