This question already has answers here:
How can I add a key/value pair to a JavaScript object?
(26 answers)
Closed 8 years ago.
I have a function like this:
function dataSend(type, message) {
return {
type: message
};
};
Which I am using like this:
io.sockets.emit('addToQueue', dataSend('error', 'User not found'));
But when it gets to the client side I get an object that is like
{ type: 'User not found' }
instead of
{ 'error': 'User not found' }
Why is this acting like this? I'm not sure how to fix this any information would be great thanks.
You can't set the key with a variable like that, you'll need bracket notation
function dataSend(type, message) {
var obj = {};
obj[type] = message;
return obj;
};
Try this:
function dataSend(type, message) {
var a={};
a[type]=message;
return a;
}
Javascript doesn't require quotes around the property names.
Using {type:message} or {'type':message} produces the same result.
Related
This question already has answers here:
Skipping optional function parameters in JavaScript
(4 answers)
Closed 3 years ago.
I have a function which has two default parameters and one regular
parameter.
var Fields = function ($content, result = failedObject, job = true)
{
...
}
When I call Fields($content,job), job here could be true or false, the result parameter takes in the job value rather than the third parameter. Works good in the case if Fields($content,result).
Any good way to tackle this situation.
you would call Fields($content, undefined, job) to use the default value for the parameter result
if I understood your question correctly, javascript does not support named parameters natively, so you can call by Fields($content, undefined, job)
or using an object as parameter for your function instead of 3 params.
You could use a destructured argument :
var Fields = function ($content, { result = failedObject, job = true } = { }) {
...
}
Then, when you call the function :
const data = { result: anotherObject, job = false };
Fields('toto', data);
Or, in your specific case :
const data = { job = false };
Fields('toto', data); // result still is a failedObject
Pass empty/undefined/null:
Fields($content, , job);
You must switch the order(like below), or using an array and treat inside function.
var Fields = function ($content, job = true, result = failedObject, )
{
}
Im building a chrome app and I am trying to add a function inside an object inside chrome.storage.local but when im doing it it does not appear if you try to get it (all the other things appear but not the function)
But if you try to do it on a normal object like
let a = {
b: function() {
return 'This is working'
}
};
then it works.
It wouldn't be a problem if I could just use eval but due to security on the chrome app it does not work.
What im trying to do is:
chrome.storage.local.set({
'obj': [{
example: 'hello',
fn: function() {
return 'This is not working'
}
}]
});
Then if you do
chrome.storage.local.get('obj', function(e) {
console.log(e.obj)
});
Then it will return with
Array (length 1): example: "hello"
and not the function,
Thanks.
Store arguments and the body like this
{function:{arguments:"a,b,c",body:"return a*b+c;"}}
Retrieve it and instantiate the function:
let f = new Function(function.arguments, function.body);
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I'm writing a simple word game to practice my javascript (I'm new to it) using the NPM package prompt (https://www.npmjs.com/package/prompt) to query the user when I need a response.
Since I come from an OOP background (in other languages) I've been experimenting with encapsulating different functionalities in different objects. So I have all the prompt related code in one object, like this
function Prompter() {
this.getUserName = function (callback) {
var schema = {
properties: {
name: {
description: "Tu nombre por favor:",
pattern: /^[ñÑa-zA-Z\s\-]+$/,
message: 'Solo letras, por favor',
required: true
}
}
};
prompt.get(schema, callback);
};
}
and game logic in another object like this (this is the relevant part of the code)
function Game() {
this.qGenerator = null;
this.prompter = null;
this.user = "";
this.doNextRound = function () {
//// omitted for brevity
};
this.init = function () {
this.qGenerator = new QuestionGenerator();
this.prompter = new Prompter();
};
this.startGame = function () {
this.prompter.getUserName(this.storeUserName);
};
this.storeUserName = function (err, result) {
if (err) {
this.handleErr(err);
return;
}
this.user = result.name;
this.doNextRound();
};
}
and I start the game like this
const game = new Game();
game.init();
game.startGame();
The problem I have is that in the Game method storeUserName, which I've passed as a callback to prompt, I have no access to the Game object through this, and thus, when I call
this.doNextRound
inside of storeUserNameI get
TypeError: this.doNextRound is not a function
I understand why, as this refers to Node inside the callback. But I don't know how to keep a reference to the correct this inside the method I'm passing as callback. I understand how to do it in more 'vanilla' Javascript -- using that = this, or apply,etc, but I'm not sure what the best way to handle this inside Node callbacks is when you're passing another object's methods. Any advice much appreciated.
Use Function.prototype.bind:
this.prompter.getUserName(this.storeUserName.bind(this));
or an arrow function:
this.prompter.getUserName( _ => this.storeUserName() );
Either of those will work.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
export class myclass implements OnInit {
private outagesList;
private outageArray;
constructor(private outages: OutagesService){}
ngOnInit(){
this.outages.getOutagesList().subscribe((data) => {
this.outagesList = data;
this.outagesList.forEach( function (arrayItem)
{
this.outageArray.push(arrayItem["title"]);
});
)
}
If i try to push the data into outageArray it is throwing ERROR TypeError: Cannot read property 'outageArray' of undefined
How can i avoid this error? I need to access this outageArray value to html.
Use an arrow function
this.outagesList.forEach((arrayItem) => {
this.outageArray.push(arrayItem["title"]);
});
Once you are using post-ES6 Javascript, functions like forEach are not likely to be your best solution. The easiest way to do this is with a for..of loop:
this.outages.getOutagesList().subscribe((data) => {
this.outagesList = data;
for (let arrayItem of this.outagesList)
{
this.outageArray.push(arrayItem.title);
});
)
I'm attempting to create a function lookup in Javascript essentially mapping a data type to a function that does something for that data type. Right now I have something similar to:
var Namespace = Namespace || {};
Namespace.MyObj = function () {
var stringFunc = function(someData) {
//Do some string stuff with someData
};
var intFunc = function(someData) {
//Do some int stuff with someData
};
var myLookUp = {
'string': stringFunc,
'int' : intFunc
};
return {
PublicMethod: function (dataType, someData) {
myLookUp[dataType](someData);
}
};
} ();
When I invoke Namespace.MyObj.PublicMethod(dataType, someData) I get an error that myLookUp is not defined. I'm assuming I'm not going about setting up the function lookup object correctly, but not sure how to do so. Thanks for any help.
The problem might simply be incorrect case
myLookup[dataType](someData);
should be (notice the capital U)
myLookUp[dataType](someData);
Just looked at my post after I wrote it up, stupid oversight, I'm declaring the properties as strings, instead of just properties.
....
var myLookUp = {
string: stringFunc,
int: intFunc
};
....
Fixes the issue.
Some additional follow up, in my actual code dataType is the result of a jQuery select. Don't know why or if this would be browser dependant (I'm using FireFox), but using double quotes around the property definition works, single quotes does not, and no quotes works as well. :-\