function doesn't read the object - javascript

can some one please tell me how can i make the send function read the email object from the next code?
var email = {
to: 'google#gmail.com',
subject: 'new email',
text: 'helloWorld'
}
function send() {
var sendMe = new email();
console.log(sendMe.subject);
}
send();​
i get this error i also tried to declare the email as follow :
var email = new object();
and it didn't work
Uncaught TypeError: object is not a function

You are either trying to do this:
var email = { to: 'google#gmail.com', subject: 'new email', text: 'helloWorld' }
function send()
{
console.log(email.subject);
}
send();
Or this
function email()
{
this.to = 'google#gmail.com';
this.subject = 'new email';
this.text = 'helloworld';
}
function send()
{
var sendMe = new email();
console.log(sendMe.subject);
}
send();
I'm not sure which, so I made an example of both. Cheers

It sounds like you want sendMe to point at the same data email is holding:
var email = { ...} ;
function send() {
var sendMe = email;
console.log(sendMe.subject);
}
But if this is the case, you might as well skip the extra variable and just use email directly:
var email = { ...} ;
function send() {
console.log(email.subject);
}

You can't use an identifier as an object constructor unless it's a function.
If you want a reference to the object that you created, just copy it from the variable:
var sendMe = email;

You have to return object:
var email = function() {
return {
to: 'google#gmail.com',
subject: 'new email',
text: 'helloWorld'
}
};
and then
function send() {
var sendMe = new email();
console.log(sendMe.subject);
}
should work.

Related

Javascript insert prompt value to another function object

I'm trying to put the values at addUser function to push to another function object. I dont how and what to put at the prompt value to .id and .pwd.
var memArray =[];
function addUserObject(id, password){
this.id = id;
this.pwd = password
}
var addUserObj = new addUserObject ("")
// i dont how and what to put the prompt value to .id and .pwd
memArray.push(addUserObj);
console.log(memArray)
function addUser(){
var addUsername = prompt ("Type your username");
var addPwd = prompt ("Type your password");
addUserObject(addUsername,addPwd)
At the risk of not having understood your problem, you can't add the user until you know the username and password (until the prompt requests are finished).
Is this what you are trying to do?:
// Initialize an empty array
var memArray =[];
// Define helper function to add a user to the array
function addUserObject(id, password){
// Define a user object
var userObj = {
id: id,
password: password
};
// Push the new user into the array
memArray.push(userObj);
}
// Define a function that requests user and pwd
function addUser(){
// Request username and pwd
var addUsername = prompt ("Type your username");
var addPwd = prompt ("Type your password");
// Call to add the user to the array
addUserObject(addUsername, addPwd);
}
// Call the 'addUser' function to request a new user
addUser();
// Print the array to console (it should contain one user)
console.log(memArray);
I have commented the code excessively just so you understand.
One way is to add the functionality to this, same as the properties you create:
function addUserObject(id, password){
this.id = id;
this.pwd = password;
this.addUsername = function(){this.id = prompt("Type your username")}.bind(this);
this.addPwd = function(){this.pwd = prompt("Type your password")}.bind(this);
};
var addUserObj = new addUserObject();
//REM: Adding username
addUserObj.addUsername();
console.log(addUserObj);
//REM: Adding paddword
addUserObj.addPwd();
console.log(addUserObj);
The second way is to ask for it on creation:
function addUserObject(id, password){
this.id = id;
this.pwd = password;
}
var addUserObj = new addUserObject(prompt("name?"), prompt("pw?"));
console.log(addUserObj);
Once you create an object, it has to contain properties along with methods, so it's ok to implement all inside an instance.
var memArray =[];
function addUserObject(){
var id, pwd;
this.getData = function(){
return {
id: this.id,
pwd: this.pwd
}
}
this.setData = function(){
this.id = prompt ("Type your username");
this.pwd = prompt ("Type your password");
}
return this.setData();
}
var user = new addUserObject;
memArray.push(user.getData());
console.log(memArray)
If you want to use constructors functions, then you can create a function which return a new object:
function userObject(id, name, password){
this.id = id;
this.name = name;
this.pwd = password
}
let userBob = new userObject(1, 'Bob', 'fooPsw');
let userJoseph = new userObject(2, 'Joseph', 'barPsw');
let userJohn = new userObject(3, 'John', 'barPsw');
and then just push these objects into array:
let users = [];
function addUser(id, name, password)
{
let user = new userObject(id, name, password);
users.push(user);
}
addUser(1, 'Bob', 'fooPsw');
addUser(2, 'Joseph', 'barPsw');
addUser(3, 'John', 'barPsw');
The whole code looks like this:
function userObject(id, name, password){
this.id = id;
this.name = name;
this.pwd = password
}
let users = [];
function addUser(id, name, password)
{
let user = new userObject(id, name, password);
users.push(user);
}
addUser(1, 'Bob', 'fooPsw');
addUser(2, 'Joseph', 'barPsw');
addUser(3, 'John', 'barPsw');
console.log(users);

how to access a variable from outside a function/instance

I have this very simple JavaScript code that should return a Fullname using parameters firstname and lastname All works fine when I alert out the fullname within the function. But I'm struggling how to make the fullname variable accessible from outside the function/instance?
here's my code:
var getName = function () {
this.name = function (firstname, lastname, success) {
var fullName = firstname + " " + lastname;
success(fullName);
};
};
var test = new getName();
test.name("John", "Smith", function (output) {
var fullname = output;
alert(fullname); //this works fine
return fullname; // I need this variable to be accessed from outside this function
});
var myName = fullname; //I need to create the variable here
alert(myName); //this does not work
Here's Fiddle
Thank you very much for your help.
Edit: I'm building an iPad app where I'm using cordova and javascript plugins.
One of the plugin gives me access to the file inside the device. Now, I need to be able to get the path and use it outside the callback so that I can use anywhere in the scope:
Here's the plugin code:
var FileManager = function(){
this.get_path = function(todir,tofilename, success){
fail = (typeof fail == 'undefined')? Log('FileManager','read file fail'): fail;
this.load_file(
todir,
tofilename,
function(fileEntry){
var sPath = fileEntry.toURL();
success(sPath);
},
Log('fail')
);
}
this.load_file = function(dir, file, success, fail, dont_repeat){
if(!dir || dir =='')
{
Log('error','msg')('No file should be created, without a folder, to prevent a mess');
fail();
return;
}
fail = (typeof fail == 'undefined')? Log('FileManager','load file fail'): fail;
var full_file_path = dir+'/'+file;
var object = this;
// get fileSystem
fileSystemSingleton.load(
function(fs){
var dont_repeat_inner = dont_repeat;
// get file handler
console.log(fs.root);
fs.root.getFile(
full_file_path,
{create: true, exclusive: false},
success,
function(error){
if(dont_repeat == true){
Log('FileManager','error')('recurring error, gettingout of here!');
return;
}
// if target folder does not exist, create it
if(error.code == 3){
Log('FileManager','msg')('folder does not exist, creating it');
var a = new DirManager();
a.create_r(
dir,
function(){
Log('FileManager','mesg')('trying to create the file again: '+file);
object.load_file(dir,file,success,fail,true);
},
fail
);
return;
}
fail(error);
}
);
}
);
};
}
and here's how I use it:
var b = new FileManager(); // Initialize a File manager
b.get_path('Documents','data.json',function(path){
myPath = path;
console.log(myPath); //this gives me the path of the file in the console, which works fine
return myPath; //I return the path to be accessed outside
});
var filePath = myPath; //here I need to access the path variable
console.log(filePath)// here, the path is undefined and it does not work
//Since I'm using angular services to retrieve the data from json, I'd like to pass the filePath
//this is a fraction of code for retrieving data:
return $resource('data.json',{}, {'query': {method: 'GET', isArray: false}});
//passing the value does not work
return $resource(filePath,{}, {'query': {method: 'GET', isArray: false}});
//even wrapping resource around instance does not work, it breaks the whole app
b.get_path('Documents','data.json',function(path){
myPath = path;
console.log(myPath); //this gives me the path of the file in the console, which works fine
return $resource(myPath,{}, {'query': {method: 'GET', isArray: false}});
});
Factory services:
'use strict';
angular
.module ('myApp')
.factory('getMeData', function ($resource) {
var b = new FileManager(); // Initialize a File manager
b.get_path('Documents','data.json',function(path){
myPath = path;
return myPath;
});
//below doesn't work when passing path (it is undefined)
return $resource(myPath,{}, {'query': {method: 'GET', isArray: false}});
//when wrapping it around, the app crashes
b.get_path('Documents','data.json',function(path){
myPath = path;
return $resource(myPath,{}, {'query': {method: 'GET', isArray: false}});
});
//none of the solution above work
});
If you have the name function return the result of success then you can use the return from the method.
I.e.
var getName = function () {
this.name = function (firstname, lastname, success) {
var fullName = firstname + " " + lastname;
return success(fullName);
};
};
var test = new getName();
var myName = test.name("John", "Smith", function (output) {
var fullname = output;
alert(fullname); //this works fine
return fullname; // I need this variable to be accessed from outside this function
});
alert(myName);
Define fullname outside the callback.
var getName = function () {
this.name = function (firstname, lastname, success) {
var fullName = firstname + " " + lastname;
success(fullName);
};
};
var test = new getName();
var fullname;
test.name("John", "Smith", function (output) {
fullname = output;
alert(fullname); //this works fine
return fullname; // I need this variable to be accessed from outside this function
});
alert(fullname);
Hope it helps. Fiddle
If async required:
Assuming the actual source of the code is an async one, now confirmed from your comment, you should simply process the result within the callback. The value is simply not available outside of the callback as the result arrives later.
The answers by #Jim and #bestmike007 will not work with an async operation as it returns a value from inside a callback which may occur long after the function is run. (note: #bestmike007 does have an improved answer linked in a comment).
e.g. Look at what happens here: http://fiddle.jshell.net/y1m36w9p/1/ or here http://jsfiddle.net/TrueBlueAussie/opczeuqw/1/
The only way to work with async code is in an async manner. That means you can only handle the result inside the callback:
// Get the fullname asyc and process the result
test.name("John", "Smith", function (fullname) {
alert(fullname); // you can only work with the result in here
});
An alternative is to return a jQuery promise from getName.name(), but the end result will still be a callback to do the work, but this time it would look like this:
test.name("John", "Smith").done(function(fullname){
alert(fullname); // you can only work with the result in here
});
but this is more code and complication for no extra benefit at this time.
For your specific updated example code:
I am not familiar enough with Angular to confirm this, and would need to see how getMeData is called, but you should use another callback as a parameter to the getMeData function you register:
'use strict';
angular
.module ('myApp')
.factory('getMeData', function ($resource, callback) {
var b = new FileManager(); // Initialize a File manager
b.get_path('Documents','data.json',function(path){
callback($resource(path,{}, {'query': {method: 'GET', isArray: false}}));
});
});
If async not required (obsolete option)
If (as a previous contradictory comment below said) this was not mean to to be async, then do not use callbacks at all, just simple functions/methods returning values: http://fiddle.jshell.net/y1m36w9p/2/
e.g.
var getName = function () {
this.name = function (firstname, lastname) {
return firstname + " " + lastname;
};
};
// Create a instance of the getName class
var test = new getName();
// Get the fullname asyc and process the result
var fullname = test.name("John", "Smith");
// Do what you like with the value returned from the function
alert(fullname);

Updating outside variables inside a javascript function in Node.js

I am developing a NodeJS application and encountered following problem:
I am using node module node-rest-client to issue REST requests using an API. I use post method provided by the module for my purpose. I need to fetch the json response and write it to seperate variables and return them.
I have defined returnData variable outside the client.post method. I need to update this returnData variable inside the function which is passed as a parameter to the client.post method.
But I have a scope issue here. Although I try to update the returnData variable inside that function, when execution returns from client.post function, I see that the same values I have set (in this case null, but may be any value) before calling client.post function still persists in the variable.
How can I define scope well so that I can update an outside variable inside the function which I pass as a parameter to another function? Any help would be greatly appreciated.
Following is my Code:
module.exports = function(){
require("../config");
var restClient = require('node-rest-client').Client;
var client = new restClient();
var sessionID = null,
reqID = 1;
var login = function(username, password){
var requestParams = {};
var apiParams = {};
requestParams.jsonrpc = "2.0";
requestParams.method = ZABBIX_API_METHODS.login;
apiParams.user = username;
apiParams.password = password;
requestParams.params = apiParams;
requestParams.id = reqID;
requestParams.auth = null;
var args = {
data: requestParams,
headers:{"Content-Type": "application/json-rpc"} // ask response type to be application/json-rpc
};
var returnData = {};
returnData.status = null;
returnData.data = null
client.post(ZABBIX_API, args, function(resData,rawRes){
if(rawRes.statusCode == 200){
returnData.status = rawRes.statusCode;
returnData.data = resData;
}
else{
returnData.status = rawRes.statusCode;
returnData.data = "Request Failed!";
}
reqID = reqID + 1;
console.log(returnData.data);
});
console.log("SessionID:"+getSessionID());
return returnData;
}
var functions = {
login: login
}
return functions;
}
Thank you.
.post is Async, you should do it like this,
var login = function(username, password, callback){
..................
client.post(ZABBIX_API, args, function(resData,rawRes){
if(rawRes.statusCode == 200){
returnData.status = rawRes.statusCode;
returnData.data = resData;
}
else{
returnData.status = rawRes.statusCode;
returnData.data = "Request Failed!";
}
reqID = reqID + 1;
return {login: returnData};
});
//remove all below return statements

How to get properties from an object

I'm using this code to retrieve a simple JSON object:
function userinfo() {
var user = new Object();
$.getJSON('###', function(data){
user.id = data.user.uID;
user.name = data.user.uname;
});
return user;
}
var user = userinfo();
console.log(user);
When I run console.log on the user object outside of the function, I can see the properties of the object (id, name). But when I try to console.log "user.id" or "user.name", they come up as undefined. I can't work out why this is, or what I can do to retrieve the properties without having to iterate over them.
Any suggestions?
The AJAX call to get the JSON is asynchronous, the callback function(data) isn't called until the AJAX returns, but you are reading user right after the AJAX request is sent, but before the AJAX response is received.
Try this:
function userinfo() {
$.getJSON('###', function(data){
var user = new Object();
user.id = data.user.uID;
user.name = data.user.uname;
// Do your stuff here
console.log(user);
});
}
userinfo();
Answer to comment:
Just have a function like this on the app:
function processUser(user){
console.log(user);
}
Then use it in the AJAX callback,
$.getJSON('###', function(data){
var user = new Object();
user.id = data.user.uID;
user.name = data.user.uname;
// Do your stuff here
processUser(user);
});
#Simon, you can do usual application logic in processUser() now, e.g.:
var usersList = []; // Assume this is a global for your app
function processUser(user){
usersList.push(user);
// now other parts of your app can find this user in the list
}
function userinfo(callback) {
$.getJSON('###', function(data){
callback({
id: data.user.uId,
name: data.user.uname
});
});
}
var user;
userinfo(function(newUser) {
user = newUser;
// do work with user.
});
// execution continues here before callback returns. User will not be set.
user.name // error no property name of undefined.
Here's the fix:
function userinfo() {
var user = new Object();
$.ajax({
async: false, //solution right here
url: '/login/user.html',
success: function (data) {
user.id = data.user.uID;
user.name = data.user.uname;
}
});
return user;
}
var user = userinfo();
console.log(user.id);
Works perfectly.

Uncaught TypeError: Object has no method ... Javascript

I'm having an issue where I get an error that says...
"Uncaught TypeError: Object f771b328ab06 has no method 'addLocation'"
I'm really not sure what's causing this. The 'f771b328ab06' is a user ID in the error. I can add a new user and prevent users from being duplicated, but when I try to add their location to the list, I get this error.
Does anybody see what's going wrong? The error occurs in the else statement of the initialize function as well (if the user ID exists, just append the location and do not create a new user). I have some notes in the code, and I'm pretty sure that this is partly due to how I have modified an example provided by another user.
function User(id) {
this.id = id;
this.locations = [];
this.getId = function() {
return this.id;
};
this.addLocation = function(latitude, longitude) {
this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
alert("User ID:" );
};
this.lastLocation = function() {
return this.locations[this.locations.length - 1];
};
this.removeLastLocation = function() {
return this.locations.pop();
};
}
function Users() {
this.users = {};
//this.generateId = function() { //I have omitted this section since I send
//return Math.random(); //an ID from the Android app. This is part of
//}; //the problem.
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
this.getUser = function(id) {
return this.users[id];
};
this.removeUser = function(id) {
var user = this.getUser(id);
delete this.users[id];
return user;
};
}
var users = new Users();
function initialize() {
alert("Start");
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data){
var user_id = data[0];
var latitude = data[1];
var longitude = data[2];
if (typeof users.users[user_id] === 'undefined') {
users.createUser(user_id);
users.users[user_id] = "1";
user_id.addLocation(latitude, longitude); // this is where the error occurs
}
else {
user_id.addLocation(latitude, longitude); //here too
alert(latitude);
}
}
})
}
setInterval(initialize, 1000);
Since I get the ID from the phone and do not need to generate it here (only receive it), I commented out the part that creates the random ID. In doing this, I had to add a parameter to the createUser method within Users() so that I can pass the ID as an argument from Initialize(). See the changes to createUser below:
Before, with the generated ID (the part where the number is generated is in the above code block with comments):
this.createUser = function() {
var id = this.generateId();
this.users[id] = new User(id);
return this.users[id];
};
After, with the ID passed as an argument:
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
If anyone has any suggestions I would really appreciate it. Thanks!
Here you're getting user_id by :
var user_id = data[0];
So it's a part of the json answer : maybe a string or another dictionnary, this can't be a user object. You should try to update your code in your success function inside the "if" block by :
user = users.createUser(user_id);
//The following line is a non sense for me you put an int inside
//an internal structure of your class that should contain object
//users.users[user_id] = "1";
user.addLocation(latitude, longitude);

Categories

Resources