using this keyword in object literal javascript [duplicate] - javascript

This question already has answers here:
Assigning the value of another key in javascript [duplicate]
(2 answers)
Closed 7 years ago.
According to me this is only being used if you need to call constructor like below
var dogObj = function(){
this.bark = "woof";
}
var dog1 = new dogObj();
console.log(dog1.bark);
Is there any cases where I use this on object literal?
var bark = {
this.bark = "dog"
}
Is above code valid? If yes,how do I call it?

you can use
var bark = {
bark : "dog"
}
and call it like
console.log(bark.bark)

this.bark = "woof";
Is not valid.
You have try something like below
var dog = {
bark : "dog"
}
And then you can access like console.log(dog.bark)
Once you formed any json string you can validate the sting using http://jsonlint.com/ just place your json string and the click on validate.

Related

JavaScript: How to change property of variables stored in an array [duplicate]

This question already has answers here:
How to create an object property from a variable value in JavaScript? [duplicate]
(9 answers)
Using Variable for Property Name of Object - Javascript [duplicate]
(2 answers)
Closed 4 years ago.
I have an array that contains variables that are used to control a template.
divisionsListToHide: ['showActivitiesList',
'showAssignActionplanDiv',
'showPropertiesListDiv',
'showAddActivityDiv',
'showCurrentActivity',
'editCurrentActivity'
],
I want to call a method that will set all variables contained in the divisionsListToHide array to false, i.e.
this.showAssignActionplanDiv = false;
this.showPropertiesListDiv= false;
I am trying to create a method (function) to accomplish this:
hideDivisions: function()
{
for(var i = 0;i<this.divisionsListToHide.length;i++)
{
var xx = 'this.' + this.divisionsListToHide[i]; // e.g. this.showActivitiesList
console.log(xx);
eval(xx) = false;
}
},
I was hoping to accomplish this through eval(), however, it displays "Uncaught ReferenceError: Invalid left-hand side in assignment". Any suggestion, how to accomplish this?
this is an object, and you can access its properties in two ways:
this.propertyName and this["propertyName"]. These two ways are the same, except the second one can be used with a variable just like in your case:
var prop = "propertyName";
this[prop] = false; // is equal to this["propertyName] = false, which is equal to this.propertyName = false
So try this:
hideDivisions: function()
{
for (var i = 0; I <this.divisionsListToHide.length; i++)
{
this[this.divisionsListToHide[i]] = false;
}
}

filtering on arrays in arrays, is there an elegant way of doing this? [duplicate]

This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
Closed 5 years ago.
This one has always served me well...
var myProperty = "FOO"
var expenseSelect = expenseArray.filter(function(obj){
return obj.property == myProperty
});
But now I have a situation where the obj.property is an array of properties ["FOO", "BAR", "WEE"] inside the expenseArray.
Is there a smart way to do this? Or do I have to do the whole loop inside loop thing?
If you want to check if myProperty is in the array you can do it using
var myProperty = "FOO"
var expenseSelect = expenseArray.filter(function(obj){
return obj.property.includes(myProperty);
});
using the some() method tests whether at-least one element in the array passes the test implemented by the provided function, it can be a simple an option..
var myProperty = "FOO";
var expenseArray=[];
expenseArray[0]={ property: ["FOO", "BAR", "WEE"] };
expenseArray[1]={ property: ["NoFOO", "BAR", "WEE"]} ;
var expenseSelect = expenseArray.filter(function(obj){
return obj.property.some(function(element,index,array){
return element == myProperty;
});
});
console.log(expenseSelect);

Pass an string representing an object function as callback [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 5 years ago.
This code doesn't work:
var my = {
testFunction: function(text) {
alert(text);
}
};
var functionName = "my.testFunction";
var f = window[functionName];
f('yeha');
Any idea why?
Update:
I don't know in advance the functionName. It might be 'my.testFunction' or 'my.test.another.function' etc.
I'm writing a validation handler and all my js will know is a string representing a function that could be a function inside an object.
This should work.
var my = {
testFunction: function(text) {
alert(text);
}
};
// the string can't be evaluated as nested object hierarchy.
// split it to address the several nodes and properties
var functionName = "my.testFunction".split('.');
var f = window[functionName[0]][functionName[1]];
f('yeha');

How can I convert a string to a variable name in Node.js? [duplicate]

This question already has answers here:
Use variable's value as variable in javascript
(2 answers)
Closed 8 years ago.
//Admin.js
var insertAdminFeed = function(s, id, timestamp){
var admin_att_new_key = '12345';
var admin_att_new_key2 = 'abc';
var admin_att_new_key3 = 'zyzyz';
var s = 'admin_att_new_key';
console.log(global[s]); //should print '12345'
};
exports.insertAdminFeed = insertAdminFeed;
I want to convert a string to a variable in node.js (I have many keys, and I don't want to write if/else statements for all of them) How can I do that?
This is not really possible in JavaScript.
You'd usually use an object literal to achieve similar needs.
var key = 'foo';
obj[key] = 1;
obj['foo'];
To be thorough, it is technically possible in JS using eval. But really, don't do this.
eval("var "+ name + " = 'some value';");
eval("console.log("+ name +")");

Define object by a variables string [duplicate]

This question already has answers here:
How do I make JavaScript Object using a variable String to define the class name?
(10 answers)
Using a variable value to call an array element
(7 answers)
Closed 8 years ago.
Hard to explain.. I basicly want to do the following:
var doWhat = "speak";
var speak = {
hello: function() { alert: "Hello!"; }
};
// Won't work
doWhat.hello();
It's a bad example, but you should be able to get what I mean.
Is it possible somehow ?
You can use eval(doWhat).hello();. That way the contents of doWhat will be evaluated to the object reference.
You can do something like
var doWhat = {}, str = "speak";
doWhat[str] = {
hello : function() {}
};
doWhat[str].hello();
jsName = 'PageIndexController';
//ST1
eval("if( typeof jsName === 'undefined')alert(111);");
//ST1
eval("if( typeof " + jsName + " === 'undefined')alert(222);");
//ST1 not work
//ST2 work and the output: 222;
//there are two different way using eval, we will get 2 different outcome.

Categories

Resources