Use `this` in object "Unexpected token this" - javascript

I am using an object for DOMString to set the DOM. I use this to pointed to the init but it shows Unexpected token this. I am learning javaScript. Please help me how to use it. Thank you very much.
let imageView = {
init: function () {
// store pointers to our DOM elements for easy access later
let DOMstrings = {
containerElem: '#cat',
nameElem: '#cat-name',
imageElem: '#cat-img',
countElem: '#cat-count'
},
this.catElem = document.getElementById(this.DOMstrings.containerElem);
this.catNameElem = document.getElementById(this.DOMstrings.nameElem);
this.catImageElem = document.getElementById(this.DOMstrings.imageElem);
this.countElem = document.getElementById(this.DOMstrings.countElem);
};

You have a comma after DOMstrings object which should be a semicolon.
Try this:
let imageView = {
init: function () {
// store pointers to our DOM elements for easy access later
let DOMstrings = {
containerElem: '#cat',
nameElem: '#cat-name',
imageElem: '#cat-img',
countElem: '#cat-count'
};
this.catElem = document.getElementById(DOMstrings.containerElem);
this.catNameElem = document.getElementById(DOMstrings.nameElem);
this.catImageElem = document.getElementById(DOMstrings.imageElem);
this.countElem = document.getElementById(DOMstrings.countElem);
}

Related

Javascript: call object method using string only

This code doesn't work.
var Modal = {
init: function() {
console.log("test");
}
}
var objMethod = "Modal.init";
window[objMethod]();
I saw some answers that it can be called using this but I want to know how it can be called without using the object.
Modal["init"]();
Thank you!
To call a namespaced function, you need to use a multidimensional array. In this case it would be window['Modal']['init'](), which can also be expressed by splitting the objMethod string and using array indices:
var arr = objMethod.split(".");
window[arr[0]][arr[1]]();
var Modal = {
init: function() {
console.log("test");
}
}
var objMethod = "Modal.init";
var arr = objMethod.split(".");
window[arr[0]][arr[1]]();

Adding properties to an object using function and bracket notation

I have an assignment on a basic javascript class that I'm taking and I can't seem to get this to work. I have this unit test that was given to me:
describe('AddSixthProperty', function() {
it('should add a food property with the value of bbq using bracket notation', function() {
expect(objects.addSixthProperty()['food']).to.equal('BBQ');
});
});
I was given an empty function:
// don't touch this line
var mysticalAnimal = objects.mysticalAnimal();
function addSixthElement(){
return
}
So I tried this:
var mysticalAnimal = objects.mysticalAnimal();
objects.addSixthProperty = function(){
mysticalAnimal['food'] = "bbq";
return mysticalAnimal["food"];
};
It doesn't work. Our test page doesn't pass that. Any help is greatly appreciated!
Thanks in advance!
You're returning mysticalAnimal['food'], and then the test tries to access ['food'] again, so it ends up accessing 'bbq'['food'], which is undefined. You need to just return mysticalAnimal, as well as get all your letter cases right. Here's a little proof of concept:
var objects = (function() {
var animal = { mystical: true };
return {
mysticalAnimal: function() { return animal; }
};
})();
var mysticalAnimal = objects.mysticalAnimal();
objects.addSixthProperty = function(){
mysticalAnimal['food'] = "bbq";
return mysticalAnimal;
};
var capturedAnimal = objects.addSixthProperty();
document.getElementById('result').innerText = capturedAnimal['food'];
<p id="result" />
Here is the function:
var mysticalAnimal = objects.mysticalAnimal();
objects.addSixthProperty = function(){
mysticalAnimal['food'] = "BBQ";
return mysticalAnimal;
};
// Test the function
console.log(objects.addSixthProperty()['food'])

OO Javascript Calling method from another method of same object

I'm having trouble calling a method from within another method of the same object.
Any help on what I may be missing, or what to look for, would be greatly appreciated.
var IceCream = function (flavor) {
this.tub = 100;
this.flavor = flavor;
};
IceCream.prototype = {
scoop : function () {
this.updateInventory; alert("scooping");
},
updateInventory : function () {
this.tub --;
alert(this.tub);
}
};
var vanilla = new IceCream("vanilla");
vanilla.scoop();
Convert this
this.updateInventory;
to this
this.updateInventory();
DEMO

Converting Circular Structure to JSON

I have two kinds of objects, Beam and Sample. Sample contains 2 Beams, and I have an array of Samples. I need to store the array into the local storage, so I'm calling localStorage["samples"] = JSON.stringify(samples); but I get the error "Converting Circular Structure to JSON". My object doesn't contain itself. I also tried replacing the samples object with just 1 beam object, but get the same error, and Beam only has integer and string values in it.
Edit
Here are the objects.
function FlexuralStrengthT97(result, method, beam1, beam2, waitForCuring, averageBeams) {
this.Result = result;
this.Method = method;
this.Beam1 = beam1;
this.Beam2 = beam2;
this.WaitForCuring = waitForCuring;
this.AverageOfBeams = averageBeams;
return this;
}
function FSBeam(testingMachineId, beamAge, widthU, widthC, widthL, widthAverage, depthR, depthC, depthL, depthAverage, maxLoad, fs, psi, breakOutside) {
this.TestingMachineId = testingMachineId;
this.BeamAge = beamAge;
this.WidthUpper = widthU;
this.WidthCenter = widthC;
this.WidthLower = widthL;
this.WidthAverage = widthAverage;
this.DepthRight = depthR;
this.DepthCenter = depthC;
this.DepthLeft = depthL;
this.DepthAverage = depthAverage;
this.MaxLoad = maxLoad;
this.FS = fs;
this.PSI = psi;
this.BreakOutside = breakOutside;
return this;
}
Those seem to be constructor functions, make sure to use them with the new keyword:
var beam1 = new FSBeam();
var flex = new FlexuralStrengthT97();
Otherwise, this will be window instead of the instances scope.

Returning a reference in JavaScript

Here is the code:
http://jsfiddle.net/GKBfL/
I am trying to get collection.prototype.add to return a reference such that the final alert will display testing, testing, 123, testing. Is there a way to accomplish what I'm trying to do here?
HTML:
<span id="spantest">testing, testing, 123, testing</span>​
JavaScript:
var collection = function () {
this.items = {};
}
collection.prototype.add = function(sElmtId) {
this.items[sElmtId] = {};
return this.items[sElmtId];
}
collection.prototype.bind = function() {
for (var sElmtId in this.items) {
this.items[sElmtId] = document.getElementById(sElmtId);
}
}
var col = new collection();
var obj = {};
obj = col.add('spantest');
col.bind();
alert(obj.innerHTML);​
You problem is this line:
this.items[sElmtId] = document.getElementById(sElmtId);
This overwrites the object currently assigned to this.items[sElmtId] with the DOM node. Instead, you should assign the node to a property of that object:
this.items[sElmtId].node = document.getElementById(sElmtId);
That way, obj.node will always refer to the current node:
alert(obj.node.innerHTML);
DEMO
Side note: The problem with your fiddle is also that you execute the code when the DOM is not built yet (no wrap (head)), so it cannot find #spantest. You have to run the code once the DOM is ready, either no wrap (body), onDomRead or onLoad.
Creating a reference like you need is impossible in JavaScript. The closest thing you can get is either a nested or closed object, or just copying it over, like so:
var collection = function() {
this.items = {};
};
collection.prototype.add = function(sElmtId) {
return this.items[sElmtId] = {};
};
collection.prototype.bind = function() {
for(var sElmtId in this.items) {
var element = document.getElementById(sElmtId);
for(var x in element) {
this.items[sElmtId][x] = element[x];
}
}
};
var col = new collection();
var obj = {};
obj = col.add('spantest');
col.bind();
alert(obj.innerHTML);
But it won't be truly "bound". You'll have to use nested objects if you need that kind of functionality, and it will probably defeat the point of your syntactic sugar.
http://jsfiddle.net/GKBfL/7/

Categories