Is it possible reuse function argument as an object? - javascript

Is it possible to do this?
function getVariable(elem) {
return $scope.elem;
}
or this;
function getField(field) {
return data[0].field;
}
getField('price') should return the equivalent of data[0].price and
getVariable('id') should return the value of $scope.id
Upon experimenting, I've found that for example getField('price') is looking for data[0].field as is in the function - not for data[0].price.

When using the dot notation for object property access in Javascript, it evaluates the name literally. As you discovered, it's always looking for a property named "field" or "elem".
When you want is bracket syntax, i.e.:
function getField(fieldName) {
return data[0][fieldName];
}
Same for your other function.

Try like this:
(function(){
var data = {
'id' : 123,
'name' : 'Toyata Camarry 2009',
'price' : 14500
},
fxArgObject = function(field) {
return data[field];
};
var price = fxArgObject('price');
console.log(price);
})();

Related

Javascript function at key value assignment in Angular 7

I am trying to find a solution for the next problem I encountered. I am trying to build a dynamic string by using Amchart3 in my project, and I need to do something like this:
return [{
id: 'Rate',
alphaField: 'alpha',
balloonText: function(graphDataItem, graph): String {
let stringNew = 'smth';
return stringNew;
},
}];
The problem I encountered is that the function written in the ballonText value isn't triggered (I put a breakpoint to check) and doesn't return anything when calling the function that uses the returned list.
My question is, how could I write a function like
key: function(a,b) {
return a + b;
}
in Angular 7, like it is done in Javascript?
Your problem is the way you assign the function 'value' to your key ballonText. If using es6, which lets you shorthand key/value names, you can assign the function like so:
const es6Assign = {
id: 'Rate',
myFunc(str) {
return str.toUpperCase();
}
}
// prints out HELLO
console.log('calling es6Assign func: ', es6Assign.myFunc('hello'));
If you want to do it the vanilla way, you should name the function even if its the value of a key:
const explicitAssign = {
id: 'Rate',
myFunc: function myFunc(str) {
return str.toLowerCase();
}
}
// prints out hello
console.log('calling explicitAssign func: ', explicitAssign.myFunc('HELLO'));
As to the why?; my guess is that even though to you the key is the 'name' of the function, to the code, a function that has no name doesn't exist, i.e. function() { ... } will return undefined. I added the case in the sample Fiddle so you can see what happens.

Create object with function parameters

How can i create object with function parameters?
function hell(par1, par2) {
return { par1 : par2 };
}
hell(ID, 1);
I want return { ID : 1 }
In modern JavaScript:
function hell(par1, par2) {
return { [par1] : par2 };
}
hell("ID", 1);
The brackets ([ ]) around the property name means that the name should be the value of the enclosed expression.
Note also that when you call the function, the value of the first argument should be a string. I changed your code to use "ID" instead of just ID; if you have a variable floating around named ID, of course, that'd be fine, so long as it can evaluate to a string.
This is a fairly recent addition to the language. If your code should run in old browsers, you'd have to do something like this:
function hell(par1, par2) {
var obj = {};
obj[par1] = par2;
return obj;
}

Return different values instead of undefined when key isn't found in an object

I'd like to set a property to an object using prototype, if it's possible, so that when I try to get an undefined value, it returns a default instead of undefined, like:
obj = {
lang : {en: 'hello', it:'ciao'}
}
Example 1: obj.lang.es (undefined) - I'd like to get obj.lang.en instead of undefined.
Example 2: obj.something.else - I'd like to get false instead of an error because it can't read else of undefined.
It is probably not a good idea.
Better use a root or default key:
obj = {
lang : {root: 'hello', en: 'hello', it:'ciao'}
}
So you can ask for a lang in this way:
var hi = obj.lang.es || obj.lang.root;
You can use this in combination with a getter method:
var getTranslation = function(lang) {
return obj.lang[lang] || obj.lang.root;
};
var hi = getTranslation("es");
This is not a pretty solution, but here it goes, create a prototype object that for any language defers the result to a default language. Then your particular object inherits from that prototype object and overrides any value it wants.
var languages = ['en', 'it', 'es']; // fill with every language you will ever use
var defaultLang = 'en';
var protoLang = Object.create(null);
function getDefaultLanguage(){
return this[defaultLang];
}
languages.forEach(function(language){
Object.defineProperty(protoLang, language, {
get : getDefaultLanguage
});
});
var obj = {
lang : Object.create(protoLang, {
en : { value : 'hello' },
it : { value : 'ciao' }
})
};
obj.lang.es // "hello"
obj.lang.en // "hello"
obj.lang.it // "ciao"
The thing is that you have to define every property first, that is why you need the languages array.
I agree with #DCoder. Maybe something like this:
function getLang(lang) {
var result = this.obj[lang];
if ( typeof result == 'undefined' ) {
result = this.obj.en;
}
return result;
}
You do not need ; inside object, there no content in obj.lang, instead try it like this:
obj = {
lang: {en: 'hello', it: 'ciao'}
};
if (obj.lang.hasOwnProperty("en")) {
console.log(obj.lang.en);
} else {
console.log(false);
}

could not get the property value of my object in angularJs

I get undefined whenever I get the value of a property of an object.
function run(id){
var report = services.getReportInfo(id);
var childReport = {
id: newGuid(),
parentId: report.id, // i get undefined
reportPath: report.path // i get undefined
};
...
}
services.js
angular.module('project.services').factory('services', function(){
var reports = [
{
....
},
{
....
}
];
function getReportInfo(id){
var report = reports.filter(function(element){
return element.id === id;
});
};
return{
getReportInfo: getReportInfo
};
}
Whenever I put breakpoint on my var report = services.getReportInfo(id) it could contains the correct values for each property of the my report object. However, when I get the report.id or report.path, I get undefined value.
--Edited--
Oh, I know now where I got wrong.
The getReportInfo function returns an array and I'm accessing the properties without telling from what index should it get the values for the said properties.
function run(id){
var report = services.getReportInfo(id);
var childReport = {
id: newGuid(),
parentId: report[0].id,
reportPath: report[0].path
};
...
}
I placed static index 0, since I know that the array will always have a length of 1.
You are not returning anything from the .factory method and the getReportInfo is also not returning anything. For what you are trying to do, try to use .service method:
angular.module('project.services').service('services', function(){
var reports = [
{
....
},
{
....
}
];
this.getReportInfo = function (id){
var report = reports.filter(function(element){
return element.id === id;
});
return report;
}
}
Here is a good explanation on how to use .factory and .service:
Confused about Service vs Factory
Two immediate issues with the code I can see:
1) Your factory function needs to return a value or constructor function. Right now your code is not initializing the factory to any value.
2) Your getReportInfo function also doesn't return a value, yet you are assigning the function result to a variable.
Read more here: http://docs.angularjs.org/guide/dev_guide.services.creating_services

Unfamiliar syntax in javascript object

My question:
var nsPreferences = {
property1:"",
get mPrefService()
{
return Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
},
setBoolPref: function (aPrefName, aPrefValue)
{
try
{
this.mPrefService.setBoolPref(aPrefName, aPrefValue);
}
catch(e)
{
}
},
getBoolPref: function (aPrefName, aDefVal)// Prefs.jsで使用
{
try
{
return this.mPrefService.getBoolPref(aPrefName);
}
catch(e)
{
return aDefVal != undefined ? aDefVal : null;
}
return null; // quiet warnings
},
};
In this object nsPreferences, what is this "get mPrefService(){}"? This is the first time I've seen this kind of syntax in javascript object. Would anyone tell me about this syntax?
It's a getter function. It will look like a variable when you read it:
var someService = nsPreferences.mPrefService;
It calls that function without using the regular invocation parens. You can also use the set operator to create a "setter" function for the same property:
set mPrefService(val){
this.actualVal = val;
},
nsPreferences.mPrefService = "service";

Categories