First, here is my code:
var lastUsedId = '';
var object = {
element: lastElement()
};
function lastElement() {
return lastUsedId;
}
lastUsedId = 123;
console.log(object); // returns `{element: ""}` and should `{element: 123}`
As you can see, I have defined object with key element which should contain last used element's ID. Problem is that I don't know that ID yet it comes to print the result. I can't change the value like object.element = 123 because of my robust application, so don't send comments like that. For this question, it has to bee structured like that.
My question is: can I set the value like function, which returns the variable with content changed afterward? Maybe it is stupid question, but when it is not possible just say it and I will try to find other way.
Not sure this is what you want, but you can use a getter for that:
var lastUsedId = '';
var object = {
get element() {
return lastElement()
}
};
function lastElement() {
return lastUsedId;
}
lastUsedId = 123;
console.log(object);
lastUsedId = 456;
console.log(object);
can I set the value like function, which returns the variable with
content changed afterward?
Why not keep the value as a function only
var obj = {
element: lastElement
};
console.log( obj.element() ); //this will invoke the method to get the latest value
Related
How to fix this issue?
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
push() is an operation off of an array object such as:
var x = [];
var y = new Array();
x.push("me");
y.push("you");
To tell if a variable is an array you can do console.log(typeof [variable]); to see what type it is, or alternatively just console log the variable to see the contents.
If you are not using an array, but are using a javascript object, you should add elements to it via basic assignment. Example:
var x = {}; //this works as an object
x.myNewVariable = "My new value";
After which you will be able to use and access that variable off of the object. If you later want to remove that you can do so by:
delete x.myNewVariable;
I would like to override a function of a JS object by adding it to its prototype.
var originalObject = function(){
this.someFun = function(){
// ...
}
}
var otherObj = function(){
this.otherFun = function(){
originalObject.prototype.fun = function(){
return 'This is the overwritten function.';
}
var o = new originalObject();
return o.fun()
}
}
This way when I execute new otherObj().otherFun() I have the expected result ('This is the overwritten function.'), but if the function I'm trying to add is already part of originalObject
var originalObject = function(){
this.fun = function(){
return 'This is the original function';
}
this.someFun = function(){
// ...
}
}
Then the result is not the expected one, infact new otherObj().otherFun() returns 'This is the original function'.
so, is this the only way to add the method to the prototype and override it? And most important why I can't "overwrite" the function in the prototype?
In js objects there are two levels which are depend on directly object and depend on directly prototype. And when you call a property which is in object, it starts to search from the root then looks in branches. You can see the tree belowed picture:
Because the function already existed in object, it will be called out instead of being looked for in objects prototype.
Basicly, i want "theId" to be equal to what "getId" returns. But how?
var Quiz = {
getId : function() {
var params = 1;
return params;
},
theId : getId(),
};
An object literal can't refer to properties/methods within itself, because at the time the object literal is evaluated the object doesn't exist yet. You have to do it as a two-step process:
var Quiz = {
getId : function() {
var params = 1;
return params;
}
};
Quiz.theId = Quiz.getId();
Note that that sets theId to whatever getId() returned at that time, it doesn't somehow automatically update theId if your real-world function is more dynamic than your example and potentially returns different values each time it's called.
Alternatively if the function is declared before the object you can create both object properties at once, with one being a reference to the function and the other being the result of calling it.
Seems a bit like a duplicate of Self-references in object literal declarations, but you could use a simple getter function for your property:
var Quiz = {
get theID() {
var params = 1;
return params;
}
};
I am defining the following object:
var object = {
first: $('.first').eq(),
firstPosition: first.position()
}
returns first is not defined
this.first... is also undefined
What is the correct syntax?
The correct syntax is:
var ob = {
key: value,
otherKey: value
};
You cannot access the properties of an object until it has finished being constructed.
So you need to do it in multiple steps.
var object = {};
object.first = $('.first').eq();
object.firstPosition = object.first.position();
You need to define first before the object construction.
var first = $('.first').eq();
var object = {
first: first,
firstPosition: first.position()
};
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);