Sorry for such a random title, but have no idea how to explain it better. And therefore, no idea if this is a duplicate question or not.
So, when declaring a new object, I'm looking to calculate the giga value:
var myObject = {
super : 1,
mega : 5,
uber : 100,
giga : this.super + this.mega + this.uber // super + mega + uber doesn't cut it either..
};
But this doesn't work, so, any ways of doing this while declaring, or not possible?
Hope I've made myself clear and thanks in advance!
In Javascript 1.5 you can use the get keyword to define a getter
var obj = {
super : 1,
mega : 5,
uber : 100,
get giga() {
return this.super + this.mega + this.uber;
}
};
alert(obj.giga) // 106
more on this http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/
I assume you have a really good reason for the need to do this inline, otherwise such
trickery is not really a good idea.
Here is what I came up with:
var myObject = (function(){
this.giga = this.super + this.mega + this.uber;
return this;
}).call({
super : 1,
mega : 5,
uber : 100
});
var myObject = {
super : 1,
mega : 5,
uber : 100
};
myObject.giga = myObject.super + myObject.mega + myObject.uber;
Related
I'm completely new to JS and trying to learn on my own. Using below code -
var me = {
name: {first:"justin"}
},
name = me.name;
name = {first: "alexis"};
Why would document.write(me.name.first + "</br>"); return justin?
and
why would document.write(this.name.first); doesn't return anything?
Please can you explain me?
Thanks,
Me
Just change the variable name name to other string, for example: n. Everything will work perfect.
var me = {
name: {first:"justin"}
},
n = me.name;
n = {first: "alexis"};
The reason is this.name.first will refer to window.name.first. But window.name has special usage in javascript and has to be a string.
I was just going through the code of jBox.js and came across the following snippet:
var appendImage = function(gallery, id, preload, open) {
if (jQuery('#jBox-image-' + gallery + '-' + id).length) return;
var image = jQuery('<div/>', {
id: 'jBox-image-' + gallery + '-' + id,
'class': 'jBox-image-container'
}).css({
backgroundImage: 'url(' + this.images[gallery][id].src + ')',
backgroundSize: this.options.imageSize,
opacity: (open ? 1 : 0),
zIndex: (preload ? 0 : this.imageZIndex++)
}).appendTo(this.content);
var text = jQuery('<div/>', {
id: 'jBox-image-label-' + gallery + '-' + id,
'class': 'jBox-image-label' + (open ? ' active' : '')
}).html(this.images[gallery][id].label).appendTo(this.imageLabel);
!open && !preload && image.animate({opacity: 1}, this.options.imageFade);
}.bind(this);
now my question is pertaining to a really complicated line of code that is trying to access a certain property in a array, i am talking about the below line of code:
this.images[gallery][id].src
what kind of an array is the above line really trying to access ? I have worked and accessed arrays like below:
var s = [{
a : 'name',
b : 'surname'
}];
val = s[0].a; // "name"
console.log(val);
But the syntax i have highlighted seems to have a extra bit of hierarchy. I am sorry, i am still a javascript novice and i am finding it hard to visualize how a array that gets accessed like below.
this.images[gallery][id].src
Would look like ? So well can somebody give me an example ? and explain ?
Thank you.
gallery, id might just be strings and you can use the following property accessor for those:
var gallery = 'galleryx',
id = 'idx';
var images = { 'galleryx': { 'idx': 2 } };
console.log(images[gallery][id]) // === 2
I often need to monitor the contents of variables when testing programs like this:
var anObject = {aProperty:true}; // this is just an example.
console.log('anObject.aProperty: ' + anObject.aProperty); <-- typed it twice.
I type the name of the variable into a string followed by typing the same thing again to reference the value.
It seems like an unnecessary duplication to write the same thing twice every time. Is there a way to do this by having to only write the name once using a function?
For example:
function show(value) {
console.log("'" + ??? + "':" + value):
}
so it can be used like this (or something similar):
show(anObject.aProperty);
The above is just a simple example. Basically what I'm asking is whether there is a way to get the name of the variable that was passed into a function so that the name can then be output as part of a string showing the value of the variable.
Haters are gonna hate:
http://jsfiddle.net/coma/6HTnB/
var anObject = {
aProperty: ['uno', 'dos', 'tres']
};
var log = function(object, property) {
var evil = 'object.' + property;
console.log(evil, eval(evil));
};
log(anObject, 'aProperty[2]');
Or even worse:
http://jsfiddle.net/coma/6HTnB/2/
var anObject = {
aProperty: ['uno', 'dos', 'tres']
};
var show = function(a) {
console.log(a + ':', eval(a));
};
show('anObject.aProperty[2]');
Well, eval is not evil per se, but the second approach is kind of ugly since the function needs to be in the correct scope.
Here is how I would write such a show() function:
function show(object, property) {
console.log(property + ":", object[property]);
}
To use it:
var mouse = { x: 100, y: 200 };
show(mouse, 'x');
And if you want to test it: http://jsfiddle.net/IQAndreas/c9SUm/
You don't print out the name of the object (and due to the way JavaScript variables and references work, there is no easy way to do so), you only get the name of the property you want to access. If you want the name of the object as well, you could manually print it out before listing the properties:
var mouse = { x: 100, y: 200 };
console.log("== mouse ==");
show(mouse, 'x');
show(mouse, 'y');
Which outputs:
"== mouse =="
"x:" 100
"y:" 200
You can however print the type of the object, (if you are using JavaScript's class features that is, otherwise, anything created with {} is just said to be an Object):
function show(object, property) {
var className = object.constructor.name;
console.log(className + "#" + property + ":", object[property]);
}
Sample output (assuming you have created the Mouse class):
"Mouse#x:" 100
"Mouse#y:" 200
And if you want to test it: http://jsfiddle.net/IQAndreas/c9SUm/2/
Based on coma's answer, I think this may be the solution:
function show() {
return function (value) {
console.log(value + ':', eval(value));
};
};
function aTest() {
obj = {x:1, y:2}; show()('obj');
};
function bTest() {
obj = {x:3, y:4}; show()('obj');
};
aTest(); // obj: { x: 1, y: 2 }
bTest(); // obj: { x: 3, y: 4 }
I would like to know if this is possible:
I want to access a index of an object that point for another index in the same object..
example:
var object = {
edit: function (string) {
alert(string);
},
edit2: "call default edit()"
};
object.edit2("Hello World!!");
How can I do that?
Sorry my english is.. bad
You could just do it like this
var object = {
edit : function(string){
alert(string);
},
edit2 :function(string){
this.edit(string);
}
};
object.edit2("Hello World!!");
How about this:
var object = {edit : function(string){alert(string)},
edit2 : function(string){this.edit(string)}
}
object.edit2("Hello World!!")
I think Javascript allow:
var object = {edit : function(string){alert(string)} };
object.edit2 = object.edit;
object.edit2("Hello World!!")
or scrblnrd3's solution.
This website is international, so i guess you're not the only one who don't speak very well english... (Why are you looking at me ?)
I'm working on a scoring script for contract bridge, just for giggles. I'm storing the game as an object:
var game = {
team1 : { player1 : prompt("Team 1, first player: "), player2 : prompt("Team 1, second player:") },
team2 : { player1 : prompt("Team 2, first player: "), player2 : prompt("Team 2, second player:") },
}
function deal(bid){
console.log("The bid was " + bid);
game.hand = {"bid" : bid , "made" : undefined};
score();
}
So what I'd like to do though, better than this, is to keep a history of the games played this session. I'd like to, in pseudocode, do something like this:
game.(hand + (hand.length+1))
or something kind of like that; basically auto-increment a certain object within an object. I'm not so sure an array would would here, but perhaps? I'm open to suggestions/bettering of my code.
PS - I'd prefer to do this in javascript, not jQuery, Prototype, Dojo, MooTools... or any other library. Thanks!
EDIT
Sorry, let me clarify: The result after playing 3 hands or so would be an object like this:
var game = {
team1 : { player1 : prompt("Team 1, first player: "), player2 : prompt("Team 1, second player:") },
team2 : { player1 : prompt("Team 2, first player: "), player2 : prompt("Team 2, second player:") },
hand1 : { bid : 2 , made : 2 } ,
hand2 : { bid : 1 , made : 4 } ,
hand3 : { bid : 3 , made : 1 } ,
hand4 : { bid : 2 , //and made hasn't been set yet because we're mid-hand
}
Given your pseudocode, you can do the following:
game[hand + (hand.length+1)]
i.e. game["prop"] == game.prop - both provide access to the same property.
Old question, I see but I have a need to do something similar. I'd vote up the answer but I'm not allowed.
It appears the fastest way to do this is to access the object like a hash / associative array.
var d = {};
var z = "hand";
d[z+1] = "foo";
console.log(d.hand1);
Test this out in firebug. Seems to work pretty well.
JS does not seem to have an php equivalent to force resolution of the variables as in the curley braces around an expression.
d->{z+1} = "foo"; // can't find anything like this in JS.
Hope that helps,