Refering to an element from within an object - javascript

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()
};

Related

Set value in the object with dynamic value

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

JavaScript class to populate object

I am trying to populate an object by using a JavaScript class. I am not even sure if I am doing it correctly, I am very new to JavaScript OOP.
var ImagesViewModel = {}; // Global object
function ImagesClass() {
this.addImage = function (iUrl) {
ImagesViewModel.push({ "ImageUrl": iUrl }) //< Error is here
}
}
var k = new ImagesClass()
k.addImage("http://www.yahoo.com")
k.addImage("http://www.xbox.com")
Basically I need an easy way to populate ImagesViewModel with multiple properties. Do I need to specify properties within ImagesViewModel? Maybe I can do all of this without having to specify a global variable?
I am getting the error
Object has no method PUSH
What you want is an array and not an object, push is a method on Array prototype and you are trying to use it on object.
Change:
var ImagesViewModel = {};
To:
var ImagesViewModel = [];
You can do it this way as well so that each instance of ImagesClass has its own set of images.
function ImagesClass() {
var _images = [];
this.addImage = function (iUrl) {
_images.push({ "ImageUrl": iUrl }) //< Error is here
}
this.getImages = function(){
return _images;
}
}
and use it as:
var k = new ImagesClass();
k.addImage("http://www.yahoo.com");
k.addImage("http://www.xbox.com");
var ImagesViewModel = k.getImages(); //You can either set it directly or as a property of object
console.log(ImagesViewModel);
Demo
the push method is only for Arrays, here you are trying to push() to an object, which is why it isn't working.
You will need to change var ImagesViewModel = {}; to var ImagesViewModel = [];
From a design perspective, you probably don't want your viewmodel to just be a flat array (even though you declared it as an object, as other posters pointed out).
I'd suggest declaring an array declaration to hold the images inside of your ImagesViewModel object.
var ImagesViewModel = { // ViewModel generic OBJECT
this.Images = new Array(); // prototype ARRAY object
};
function ImagesClass() {
this.addImage = function (iUrl) {
ImagesViewModel.Images.push({ "ImageUrl": iUrl })
}
}

"OOP"-JS - set propertie equal to function

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;
}
};

variable is undefined, but I have defined as property in class

I have the following code:
Javascript:
slideShow = {
ImgsFolder: "images/",
ImgsSrc: ['img.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg'],
MainElem: document.getElementById('SlideShow'),
ImgElem: (this.MainElem.firstElementChild) ? this.MainElem.firstElementChild : this.MainElem.firstChild
doit: function(){
for (i = 0; i < this.ImgsSrc.length; i++) {
document.writeln(this.ImgsFolder + this.ImgsSrc[i] + "<br/>");
}
}
}
When print the value of ImgElem variable , gives me error message this.MainElem is undefined, and the problem in the last line.
I don' know what's the problem in this part of code
As I mentioned in a comment, it is not possible to refer to the object being created via object literal notation from within the notation itself.
You need to fully create the object before you can reference it.
slideShow = {
ImgsFolder: "images/",
ImgsSrc: ['img.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg'],
MainElem: document.getElementById('SlideShow')
}
slideShow.ImgElem = slideshow.MainElem.firstElementChild ||
slideshow.MainElem.firstChild
To refer to the object during creation, you need a constructor function.
function SlideshowMaker() {
this.ImgsFolder = "images/",
this.ImgsSrc = ['img.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg'],
this.MainElem = document.getElementById('SlideShow')
this.ImgElem = this.MainElem.firstElementChild ||
this.MainElem.firstChild
}
// use "new"----v----to create a new object
var slideshow = new SlideshowMaker()
In order to use the this keyword you have to instantiate object with the new keyword. Otherwise the this keyword will point to the window object in this case.
When you use the object literals such as { key: value, ... }, the object is actually created after the whole block is parsed/executed.
var a = {
// a is not defined here
key: value
};
// it is defined here
Also, you cannot use this as a reference to the object you are about to create. this can only be used in methods of an object (functions bound to the object or executed in their context).
You have two options:
1.) You need to either create a getter function such as
var a = {
b: value,
c: function () { return this.b.c; }
};
and call it in order to access b.c: a.c()
2.) The better way in your case is to define the property ImgElem after the object is actually created:
var slideShow = {
MainElem: document.getElementById('SlideShow')
};
slideShow.ImgElem = slideShow.MainElem.firstElementChild || slideShow.MainElem.firstChild;
Notice the usage of slideShow instead of this.
Maybe you have missplaced some parentheses?
var slideShow = {
ImgsFolder: "images/",
ImgsSrc: ['img.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg'],
MainElem: document.getElementById('SlideShow'),
ImgElem: (this.MainElem.firstElementChild ? this.MainElem.firstElementChild : this.MainElem.firstChild)
}

javascript / jquery - adding properties to an instantiated object

I am instantiating an object which builds an associative array. After it is instantiated, I want to add properties the object's members, but I'm getting an error when I attempt to do so.
So this is the object, which parses a bunch of xml and builds out the scenes and vehicles arrays:
var supertree = {
scenes: {},
vehicles: {},
init: function() {
this.parseScenes();
this.parseVehicles();
},
...
And when I instantiate the object:
supertree.init();
supertree.ready = function() {
assignSpritePos();
}
I can't add properties to it. This is what I'm trying to do:
function assignSpritePos(){
var sceneCount = 0;
var sceneLength = Object.keys(supertree.scenes).length;
for (i=0; i< sceneLength; i++){
//console.log(i);
supertree.scenes[i].index = i;
sceneCount++;
}
}
As you can see, all I'm really trying to do is store some permanent reference to its index in the overall object. How do I do this? The error I get is:
TypeError: 'undefined' is not an object (evaluating 'supertree.scenes[i].index = i')
Assigning properties to objects isn't recursive, i.e. it doesn't create objects automagically for you so you must assign each property individually.
Try this...
supertree.scenes[i] = { 'index': i };
You can't assign a property to an object that doesn't exist yet. Use this:
supertree.scenes[i] = {};
supertree.scenes[i].index = i;

Categories

Resources