Object comparison help needed - javascript

I would like to compare the names, if they match, then say we have similar names, else that we have different names. But this code gives output undefined while comparing names.
Could someone please help me out to understand/fix this problem?
I want to get following, for example:
We have different names, Bob and I.
function addPersonMethods(obj){
this.obj = obj;
}
addPersonMethods.prototype.greet = function(str){
return str + ", my name is "+ this.obj.name;
}
addPersonMethods.prototype.nameshake = function(othername){
this.othername = othername;
if (this.obj.name == this.othername){
console.log("We have the same name ," + this.obj.name + " and I! ");
}
else
console.log("We have different names ," + this.obj.name + " and I.");
}
var bob_def = { name: 'Bob', age: 21 };
var eve_def = { name: 'Eve', age: 21 };
var bob = new addPersonMethods(bob_def);
var eve = new addPersonMethods(eve_def);
var another_bob = new addPersonMethods({name:'Bob', age: 40});
console.log(bob.greet("Hi all"));
console.log(eve.greet("Hello"));
console.log(another_bob.greet("Hey"));
console.log(bob.nameshake(eve));

Your nameshake() method expects a string (the name), but you're passing an object, so the comparison will never be true. You want to compare to that object's .obj.name.
Second, you're logging the result of bob.nameshake(), when the function doesn't actually return anything.
And you're printing your own name in the "We have..." statements, when you want to print the other person's.
function addPersonMethods(obj) {
this.obj = obj;
}
addPersonMethods.prototype.greet = function(str) {
return str + ", my name is " + this.obj.name;
}
addPersonMethods.prototype.nameshake = function(otherperson) {
var othername = otherperson.obj.name;
if (this.obj.name == othername) {
console.log("We have the same name, " + othername + " and I! ");
}
else
console.log("We have different names, " + othername + " and I.");
}
var bob_def = {
name: 'Bob',
age: 21
};
var eve_def = {
name: 'Eve',
age: 21
};
var bob = new addPersonMethods(bob_def);
var eve = new addPersonMethods(eve_def);
var another_bob = new addPersonMethods({
name: 'Bob',
age: 40
});
console.log(bob.greet("Hi all"));
console.log(eve.greet("Hello"));
console.log(another_bob.greet("Hey"));
bob.nameshake(eve);
bob.nameshake(another_bob);

You are comparing a string (this.obj.name) to an object (othername). They won't be equal so you will always output that they have different names. The return value of any function by default is undefined unless you specify otherwise, so that's why your output is tailed by undefined.
Either pass in eve.obj.name to the function, or extract that value inside the function so you can compare properly.

Related

Can't get value of array

Still can't understand my mistake with this code.
All what I want it - via prompt get all list of users (name / surname)
function UserList() {
let users = [];
while (true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
users.push(response.split(' '));
}
return users;
}
function User() {
this.name = userList[0];
this.surname = userList[1];
this.regDate = new Date;
for (i = 0; i < userList.length; ++i) {
console.log('Name: ' + this.name + ' Surname: ' + this.surname + '. Date of registration : ' + this.regDate)
}
}
let userList = new UserList();
let user = new User();
And I faced with a misunderstanding why I cant get first word of prompt despite I put users.push (response.split(' ')).
userList [0] - shows first index of array instead first word.
And second I want to get all list of users in console.log but instead it I get the same string depending on length of array
userList[0] in the function User will return an array: ['name', 'surname'].
To get the first name for example, you need to use this.name = userList[i][0]
function UserList() {
let users = [];
while (true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
users.push(response.split(' '));
}
return users;
}
function User() {
for (var i = 0; i < userList.length; ++i) {
this.name = userList[i][0];
this.surname = userList[i][1];
this.regDate = new Date;
console.log('Name: ' + this.name + ' Surname: ' + this.surname + '. Date of registration : ' + this.regDate)
}
}
let userList = new UserList();
let user = new User();
You are pushing an array in an other array, so your index is not correct (array looks like this: [["firstname", "lastname"]]). You could spread the items when pushing using the spread operator (...), you could also flatten the array using flat().
Also when creating a date, use new Date().
function UserList() {
let users = [];
while (true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
users.push(...response.split(' ')); // flatten
}
return users;
}
function User() {
this.name = userList[0];
this.surname = userList[1];
this.regDate = new Date(); // ()
console.log('Name: ' + this.name + ' Surname: ' +
this.surname + '. Date of registration : ' + this.regDate)
}
let userList = new UserList();
let user = new User();
Using flat()
return users.flat();
Edit
I actually understood the question wrong (thought you only wanted 1 user), the other answer should be correct and makes more sense.
UserList shouldn't be a constructor. It should just be a function that returns an array of names.
You shouldn't be iterating over the list of users within User. You should then be iterating over the array creating one new User on each iteration which should be generated from a constructor. You can just pass in each name from the array and build an new object.
function getNames() {
const users = [];
while (true) {
const response = prompt('Please, enter your first and last names');
if (response == null) break;
users.push(response.split(' '));
}
return users;
}
// Pass in a user name from the array as an argument
// It's array so we can destructure the first and last name
// immediately
function User([first, last]) {
this.first = first;
this.last = last;
this.regDate = new Date();
this.message = `Name: ${this.first}. Surname: ${this.last}. Date of registration: ${this.regDate}.`;
}
// Iterate over the array generated by `getUsers`
// and for each name create a new user.
for (let name of getNames()) {
console.log(new User(name));
}
Additional documentation
Destructuring assignment

Node.js - Promise callbacks override custom objects

This is my first post to this site, so I apologize in advance of any lack of data or tags, etc. I've been using this site for years, and it always helped me, but now I'm truly lost, and I couldn't find an answer anywhere.
I have an application where I need to call a web service 10 times, each time with a different parameter. The return payload is complex, so I created a custom object to hold the data. I need data from all 10 calls before moving forward with my code, which led me to callback hell. I'm trying to use Promises to simplify this, but this is where I'm facing this weird issue. I'm able to replicate this issue with a simple class:
Custom Object (Person):
var person = {
firstName : String,
lastName : String,
age : Number
}
function Person() { //getters and setters
} module.exports = Person;
Function getToken (returns a specific token my web service calls need), here replaced with a simple string:
function getToken() {
return new Promise(function(resolve, reject) {
var x = "random token";
console.log('getting token');
setTimeout(function(){resolve(x)}, 200);
});
}
Function getAction: in my real app, it calls the web service. Here it just creates a random person with an ID as input:
function getAction(uuid) {
return new Promise(resolve => {
var newPerson = new Person();
newPerson.setFirstName("John " + uuid);
newPerson.setLastName("Doe");
newPerson.setAge(20);
console.log("---> Returning Person " + newPerson.getFirstName());
setTimeout(function(){resolve(newPerson)}, 300);
});
}
Function getActions: calls getAction for each input parameter. This function itself must return a Promise because there's another function waiting for all the data to be available before continuing.
function getActions() {
return new Promise(function(resolve, reject) {
getToken().then(async function(tokenret) {
var userIds = ["001", "002", "003", "004", "005", "006", "007", "008", "009", "010" ];
var myPromise = Promise.join;
myPromise(getAction(userIds[0]), getAction(userIds[1]), getAction(userIds[2]), function(personOne, personTwo, personThree) {
console.log("Person One: " + personOne.getFirstName());
console.log("Person Two: " + personTwo.getFirstName());
console.log("Person Three: " + personThree.getFirstName());
});
}).catch(function(rej) {console.log("Promise Failed! " + rej);});
});
}
The output for this execution is:
---> Returning Person John 001
---> Returning Person John 002
---> Returning Person John 003
Person One: John 003
Person Two: John 003
Person Three: John 003
We can see that the getAction function was executed in the right order, with the right parameters. But all 3 variables created in the getActions function have the value from the last execution.
I also tried this code:
const allPromises = userIds.map(userIds => getAction(userIds));
await Promise.all(allPromises).then(function(allResults) {
console.log("Received " + allResults.length + " records");
var thisPersonZero = allResults[0];
console.log("This person 0: " + thisPersonZero.getFirstName());
var thisPersonOne = allResults[1];
console.log("This person 1 " + + thisPersonOne.getFirstName());
var thisPersonTwo = allResults[2];
console.log("This person 2 " + + thisPersonTwo.getFirstName());
console.log("Recapping");
console.log("This person 0: " + thisPersonZero.getFirstName());
console.log("This person 1: " + thisPersonOne.getFirstName());
console.log("This person 2: " + thisPersonTwo.getFirstName());
});
And I got this output:
---> Returning Person John 001
---> Returning Person John 002
---> Returning Person John 003
---> Returning Person John 004
---> Returning Person John 005
---> Returning Person John 006
---> Returning Person John 007
---> Returning Person John 008
---> Returning Person John 009
---> Returning Person John 010
Received 10 records
This person 0: John 010
This person 1 John 010
This person 2 John 010
Recapping
This person 0: John 010
This person 1: John 010
This person 2: John 010
Finally, I tried using await, which generated even weirder results:
var firstPerson = await getAction(userIds[0]);
console.log("First Person: " + firstPerson.getFirstName());
var secondPerson = await getAction(userIds[1]);
console.log("Second Person: " + secondPerson.getFirstName());
console.log("Recapping");
console.log("First Person: " + firstPerson.getFirstName());
console.log("Second Person: " + secondPerson.getFirstName());
Result:
---> Returning Person John 001
First Person: John 001
---> Returning Person John 002
Second Person: John 002
Recapping
First Person: John 002
Second Person: John 002
So the value is correct, until the callback for the next Promise, which replaces the value for all the variables. The behavior is the same if I create copies of the variable, even using JSON.parse(JSON.stringify()).
This code works perfectly if I use strings instead of the Person object. However it would be extremely cumbersome to try and do this without custom objects.
I'm sure that I am making some very basic mistake, but even though this seems to be very straightforward, I couldn't find anything on this particular issue anywhere. This issue is happening with Node versions 9.5 and 10, running on MacOS (if it makes any difference).
Any help will be very much appreciated. Thanks in advance!
Full code snippet:
// Person.js
var person = {
firstName : String,
lastName : String,
age : Number
}
function Person() {
Person.prototype.setFirstName = function(firstName) { person.firstName = firstName; }
Person.prototype.setLastName = function(lastName) { person.lastName = lastName; }
Person.prototype.setAge = function(age) { person.age = age; }
Person.prototype.getFirstName = function() { return (typeof person.firstName === 'undefined') ? '' : person.firstName; }
Person.prototype.getLastName = function() { return (typeof person.lastName === 'undefined') ? '' : person.lastName; }
Person.prototype.getAge = function() { return (typeof person.age === 'undefined') ? 0 : person.age; }
}
module.exports = Person;
// Error.js
var Promise = require('bluebird');
var Person = require("./models/Person");
function getToken() {
return new Promise(function(resolve, reject) {
var x = "random token";
console.log('getting token');
setTimeout(function(){resolve(x)}, 200);
});
}
function getActions() {
return new Promise(function(resolve, reject) {
getToken().then(async function(tokenret) {
var userIds = ["001", "002", "003", "004", "005", "006", "007", "008", "009", "010" ];
/*
var myPromise = Promise.join;
myPromise(getAction(userIds[0]), getAction(userIds[1]), getAction(userIds[2]), function(personOne, personTwo, personThree) {
console.log("Person One: " + personOne.getFirstName());
console.log("Person Two: " + personTwo.getFirstName());
console.log("Person Three: " + personThree.getFirstName());
});
*/
var firstPerson = await getAction(userIds[0]);
console.log("First Person: " + firstPerson.getFirstName());
var secondPerson = await getAction(userIds[1]);
console.log("Second Person: " + secondPerson.getFirstName());
console.log("Recapping");
console.log("First Person: " + firstPerson.getFirstName());
console.log("Second Person: " + secondPerson.getFirstName());
/*
const allPromises = userIds.map(userIds => getAction(userIds));
await Promise.all(allPromises).then(function(allResults) {
for (var x = 0; x < allResults.length; x++)
{
var thisPerson = allResults[x];
console.log("This Person: " + thisPerson.getFirstName());
}
console.log("Received " + allResults.length + " records");
var thisPersonZero = allResults[0];
console.log("This person 0: " + thisPersonZero.getFirstName());
var thisPersonOne = allResults[1];
console.log("This person 1 " + thisPersonOne.getFirstName());
var thisPersonTwo = allResults[2];
console.log("This person 2 " + thisPersonTwo.getFirstName());
console.log("Recapping");
console.log("This person 0: " + thisPersonZero.getFirstName());
console.log("This person 1: " + thisPersonOne.getFirstName());
console.log("This person 2: " + thisPersonTwo.getFirstName());
});
*/
}).catch(function(rej) {console.log("Promise Failed! " + rej);});
});
}
function getAction(uuid) {
return new Promise(resolve => {
var newPerson = new Person();
newPerson.setFirstName("John " + uuid);
newPerson.setLastName("Doe");
newPerson.setAge(20);
console.log("---> Returning Person " + newPerson.getFirstName());
setTimeout(function(){resolve(newPerson)}, 300);
});
}
getActions();
Without going too much into your code, I can already tell you that your Person 'class' methods are using person object declared at the top of the Person.js file. Fix those to use this and that should be it.
Person.prototype.setFirstName = function(firstName) { this.firstName = firstName; }
The way you have it set now the methods keep mutating the same object.

Input value checked as unique and then added to Object Array - JavaScript

So I'm trying to design a form that will have 3 input fields (Cust ID, Cust Name and Amount), the ID would need to be checked if it exists in the Object Array, and if so throw an error, otherwise it would add all 3 values to the Object Array.
I need to use an object so that I don't use a multitude of Arrays, however I've never actually used an Object based Array, so if anyone is able to provide an example of how to use it that would be a massive help!
var garrCust = {id:"", name:"", amount:""};
function addCust(){
var custID = document.getElementById("custid").value;
var custName = document.getElementById("custname").value;
var amount = document.getElementById("amount").value;
if(!custID){
document.getElementById("output").innerHTML = "ID Cannot be Blank";
return false;}
document.getElementById("output").innerHTML += "<br />Added " + custID + "<br /><br />";
document.getElementById("output").innerHTML += "List contains: " + garrCust.id;
return true;
}
I would use an ID to name-and-amount object map to simplify and speed-up the lookup:
var garrCust = []; // an array of id -> {id:"", name:"", amount:""}
function addCust(){
var custID = document.getElementById("custid").value;
var custName = document.getElementById("custname").value;
var amount = document.getElementById("amount").value;
if(!custID){
document.getElementById("output").innerHTML = "ID Cannot be Blank";
return false;
}
if (!garrCust[custID]) {
// ID not found in the array
garrCust[custID] = { id: custID, name : custName, 'amount' : amount};
document.getElementById("output").innerHTML += "<br />Added " + custID + "<br /><br />";
} else {
document.getElementById("output").innerHTML += "List contains: " + garrCust.id;
}
return true;
}
NOTE: Storing ID as part of object is actually optional as it is already associated with an entry as an array index
You may also use a constructor to define the object content and the id as the property to index them like so:
// Create an object with the two properties name and amount
function Customer(name,amount) {
this.name = name;
this.amount = amount;
}
// Declare some variables
var id, c;
var customers = {};
// Sample names
var name = [ 'one','two','three','four','five' ];
// Create five sample entries - reusing id for amount
for (id = 0; id < 5; id++) {
// Using the new keyword with customer creates the object with
// the data you pass
customers[id] = new Customer(name[id],id);
}
// A loop to test for the presence of customer ids
for (c = 0; c < 5; c++) {
id = Math.floor(Math.random() * 20);
if (customers.hasOwnProperty(id)) {
console.log(id+" exists");
} else {
console.log(id+" does not exist");
}
}
This would create an object that had objects as properties, and the name of the properties is the customer id.
customers = { 44: { name: "John", amount: 6 },
33: { name: "Sally", amount: 5}};
To display the customer list, you may use the following:
var html;
// Use a template literal to build the list item for each customer
function listTemplate(id,name,amount) {
return `<li><span class="id">${id}</span>
<span class="name">${name}</span>
<span class="amount">${amount}</span></li>`;
}
html = "<ul>";
// Iterate through all the customers
for (id in customers) {
c = customers[id];
// Concatenate the list items
html += listTemplate(id,c.name,c.amount);
}
html += "</ul>";
// Add the HTML into the DOM
document.getElementById("customer-list").innerHTML = html;

Proper approach for complex / nested JavaScript-object creation within another object

The following code is meant to be a short example for a simple construct of a reusable object. This is a very simple, one level depth object, put as many props and methods as you like and just assign them.
function someDesiredReusableType(optionally, pass, ctor, pars, here) {
//core obj to return
var DesiredTypeCrtor = {
propSkiingLocation: "canada",
OrderTickets: function(optionally){
var tryRoomWView = optionaly;
print(
"Dear " + ctor +", your request for " +
propSkiingLocation + " is now being processed: an " +
tryRoomWView + " request was notified, we understand you have " + pars + " for cross country transportation, confirmation email will be sent " + here + " as soon as we process your order. }
}
};
return DesiredTypeCrtor
}
Here is an example of this use:
var DesrVacSkC = someDesiredReusableType("could really help!",null, "mr. Bean", "my mini", "Fun#bbc.co.uk")
//oh..almost forgot
DesrVacSkC.OrderTickets();
As this imaginative object, is actually not as simple as I did use in my code, it does work as is (didn't try this actual one, as it's just an example.)
But this next setup that is similarly using the same approach is buggy somewhat.
This is an example for an object I have successfully and in a blink of an eye implemented as a nested object using the exact same approach as the buggy object, which I do not understand why they Applied the not with same approach by the browser.
//this is an important one, a smart property / value holder I came up with and does work perfectly, as a nested member.
function Rprp(parVal) {
var cretdprp = {
propVal: parVal,
propValAsint: parseInt(parVal)
};
return cretdprp;
}
But the next one, here below, does not, as it lacks the proper approach for the initialization of ownedFefCollCore
Uncaught TypeError: Cannot read property 'HElmTColl' of undefined
//this is an important one, that was started as a very good one, with adding it to the object below, up until I have added ownedFefCollCore member.
function CreateFileEditForm_Manager() {
//as i do usually base/inner/creator and a return obj
var Repo = {
CsDataLocals:
{
GetCurLastfileId:Rprp($("#HLocModelData_LastFileId").val())
},
FormFldNames:
{ JRdrData_FileName: "JRdrData_FileName" },
//this is my bugg ! with and without new keyword & as function or Object!!
ownedFefCollCore: new FefCollCore(),
//and this is the line that chrome get's is anger on --> all day long
FeFDivWFldsColl: this.ownedFefCollCore.HElmTColl,
FeFDivWFlds_IdColl: this.ownedFefCollCore.HElmT_IdColl,
FeFDivWFldsCollAdd: function (parId, parFefDivWrpDivflds) {
this.ownedFefCollCore.CollAdd(parId, parFefDivWrpDivflds);
},
/ ........
//some more code was removed trying to keep it as short as possible
}
//fefa stands for fileRecord Edit Form , core just says nothing, is there to imply the 'thing' is to be shared between variation of instances from the base object
I found the following approach in my research for less error prone constructs, but even this one does not correct the bug. And it was found among some others, such as this Object.create()
var FefCore = JClassProto({
initialize: function () {
this.HElmTColl = new Array();//was originally [] ...
//i changed because i wanted to eliminate any doubt that it's one of the reasons my code is ... Somewhere undefined , now i know (pretty sure they might be little different but both are ok.) it's not it.
this.HElmT_IdColl = new Array();
this.CollAdd = function (parId, parHElmT) {
this.HElmTColl.push(parHElmT);
this.HElmT_IdColl.push(parId);
}
this.Coll_Remove = function (parHElmT) {
this.HElmTColl.pop(parHElmT);
}
// this is the first move, if a new object(which is an element in the array) about to be created,
// call this to make sure not exist for i create do
this.ElmObjCanCreate = function (parId) {
return this.getIndexOfValuInDivWFldsColl(parId) < 0;
}
this.HElmTColl_FindById = function (parId) {
var collindexofCurFileReadyDivWrpFlds = this.getIndexOfValuInDivWFldsColl(parId);
return this.HElmTColl[collindexofCurFileReadyDivWrpFlds];
}
this.getIndexOfValuInHElmTColl = function (parId) {
return $.inArray(parId, this.HElmT_IdColl);
}
}
});
And last but not least, my original code (right after the attempt to create it as a base /shared object).
function FefCollCore() {
this.Cr = {
HElmTColl: new Array(),
HElmT_IdColl: new Array(),
CollAdd: function (parId, parHElmT) {
this.HElmTColl.push(parHElmT);
this.HElmT_IdColl.push(parId);
},
Coll_Remove: function (parHElmT) {
this.HElmTColl.pop(parHElmT);
},
CollNeedCreate: function (parId) {
return this.getIndexOfValuInDivWFldsColl(parId) < 0;
},
HElmTColl_FindById: function (parId) {
var collindexofCurFileReadyDivWrpFlds = this.getIndexOfValuInDivWFldsColl(parId);
return this.HElmTColl[collindexofCurFileReadyDivWrpFlds];
},
getIndexOfValuInHElmTColl: function (parId) {
return $.inArray(parId, this.HElmT_IdColl);
}
};
return this.Cr;
}
//and this is the line that chrome get's is anger on --> all day long
FeFDivWFldsColl: this.ownedFefCollCore.HElmTColl,
If interpret Question correctly, you could try to set FeFDivWFldsColl as a function that returns this.ownedFefCollCore.HElmTColl
var FefCore = function() {
this.e = new Array();
this.e.push(2);
}
function CreateFileEditForm_Manager() {
var Repo = {
a: 0,
b: 1,
c: new FefCore(),
// set `FeFDivWFldsColl` value as a function
d: function() {
// `this.c` : `new FefCore()` , `this.c.e` : `new Array()`
return this.c.e
}
};
return Repo
}
var Fef = new CreateFileEditForm_Manager();
console.log(Fef.d())
var cont = "...see console";
var DivEmptyhtml = document.createElement('div');
var elmst = document.createElement('style');
function stringcss (){
return ".cssEmptyhtml{ \r\n\tmargin:auto; margin-top:10px; margin-bottom:20px;"+
" text-align:center; top:10px;"+
" width:40%; padding: 5px; height: 100px; " +
"background-color:rgb(96,116,243); "+
"color: #B5fee8; "+
"background-image:" +
" linear-gradient(to right bottom, #2983bC 24%, #284a4b 77%);"+
" box-shadow: 8px 10px 50px 20px rgb(55, 55, 55); "+
" -webkit-border-radius:10px;border-radius:10px; }";
}
//elmst.innerHTML = stringcss();
DivEmptyhtml.innerHTML = cont;
DivEmptyhtml.className = "cssEmptyhtml";
DivEmptyhtml.attributes["id"] ="DivEmptyhtml";
$("head").append(elmst);
$("body").append(DivEmptyhtml);
$(elmst).attr("id","elmst");
//$(".cssEmptyhtml").attr("style",stringcss());
$(elmst).text(stringcss());
var strS, strF, message;
var indx = 123;
var count = 135;
indx = ++count - 1;
var init = true;
//now me
var programSteps = 0;
var starting = "starting";
console.log(starting);
function Log(strLine) {
var d = new Date,
DS = d.getSeconds(),
Dms = d.getMilliseconds().toString();
console.log("[step#" + (++programSteps) + "] " + DS + "." + Dms.substring(0, 2) + "> " + strLine);
}
//...see console
function LogObj(p_type) {
function Fnl_t_t() {
this.obj = "\r\n\t\t";
}
function Fnl_5xt() {
this.obj = "\r\n\t\t\t\t";
}
var obj = {
doNewLineBold: function(boolPrint, value, value2, value3, value4) {
var nlttcopy = this.backnl_t_t.obj;
this._nl_t_t = lnobj1.backnl_5xt.obj+ "|========> [ " + value;
this._nl_t_t += value2 != "" ? " " + value2 : "";
this._nl_t_t += value3 != "" ? " " + value3 : "";
this._nl_t_t += value4 != "" ? " " + value4 : "";
this._nl_t_t += " ] <=============|" + nlttcopy;
if (boolPrint) {
Log(this._nl_t_t);
return "";
} else return this._nl_t_t;
},
doLineBold: function(boolPrint, value, value2, value3, value4) {
var nlttcopy = this.backnl_t_t.obj;
this._nl_t_t = "|========> [ " + value;
this._nl_t_t += value2 != "" ? " " + value2 : "";
this._nl_t_t += value3 != "" ? " " + value3 : "";
this._nl_t_t += value4 != "" ? " " + value4 : "";
this._nl_t_t += " ] <=============|" + nlttcopy;
if (boolPrint) {
Log(this._nl_t_t);
return "";
} else return this._nl_t_t;
},
_type: {
val: p_type,
formated: ""
},
doformatedHeader: function() {
var splts = this._type.val.split(' ');
for (var i = 0; i < splts.length; i++) {
this._type.formated += splts[i] + this.ErowR;
}
return "|========> [ " + this._type.formated +
" ] <=============|" + this.backnl_5xt.obj;
},
doformatedTail: function() {
return this.backnl_5xt.obj + "|========> [ END_ " + this._type.formated + "_END] <=============|" + this.backnl_t_t.obj;
},
_nl_t_t: function() {
return "\r\n\t\t";
},
backnl_5xt: new Fnl_5xt(),
backnl_t_t: new Fnl_t_t(),
ErowR: ">",
nlArowR : new Fnl_5xt().obj + ">"
};
return obj;
}
var lnobj1 = LogObj("listWcounter1() arr"); //create object #1
var lnobj2 = LogObj("listWcounter2() arr"); //make sure #2 is not a-copy
var header1 = lnobj1.doformatedHeader();
var Tail1 = lnobj1.doformatedTail();
var header2 = lnobj2.doformatedHeader();
var Tail2 = lnobj2.doformatedTail();
var nlarowR1 = lnobj1.backnl_5xt.obj + lnobj1.ErowR;
var nlarowR2 = lnobj2.backnl_t_t.obj + lnobj2.ErowR;
Log(header1 + lnobj1.ErowR + " starting1... " + nlarowR1 + " is init1 ok?, and index1 is Ok? " + indx + Tail1);
Log(header2 + lnobj2.ErowR + " starting2... " + nlarowR1 + " is init2 ok?, and index2 is Ok? " + indx + Tail2);
var newbold = lnobj1.doLineBold(0, "a", "b", "c", "d") + lnobj1.backnl_5xt.obj;
Log("newbold looks Like: " + newbold);
lnobj1.doLineBold(1, "A", "B", "C", "D");
lnobj1.doNewLineBold(1, "e", "f", "g", "h");
Log(lnobj1.nlArowR);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Javascript passing a callback with local references

An example can be seen on this JSFiddle
I'm creating an instance, changing one of the functions of that instance, and then calling that function within a different function in that instance. I'm having difficulty accessing local and instance variables inside the updated function.
Code
var MyObj = function (name) {
var that = this;
MyObj.myObjs = (MyObj.myObjs || []),
this.objName = name,
this.objIdx = MyObj.myObjs.length;
MyObj.myObjs.push(this.objName);
this.doOnSetName = function () {};
this.setName = function (name) {
that.doOnNameSet();
that.objName = name;
MyObj.myObjs[that.objIdx] = name;
}
}
var obj1 = new MyObj("obj1");
//obj1.doOnNameSet = function() { alert("objName: "+this.objName) };
//obj1.setName("obj1");
var obj2 = new MyObj("obj2");
obj2.doOnNameSet = function () {
$("#console").append("Old objName: " + this.name
+ "<br />New objName: " + name + "<br />")
};
obj2.setName("obj2 - changed");
$("#console ").append("Objects: <br />*" + MyObj.myObjs.join(", <br />*"));
Actual Outcome
Old objName: undefined
New objName: result
Objects:
*obj1,
*obj2 - changed
Desired Outcome
Old objName: obj2
New objName: obj2 - changed
Objects:
*obj1,
*obj2 - changed
that.objName = name;
MyObj.myObjs[that.objIdx] = name;
that.doOnNameSet();
means that the old name is already forgotten when the listener is called. I'm not sure how you did intend to get it. Maybe call the listener before you change it, with the new name as an argument.
obj2.doOnNameSet = function () {
$("#console").append("Old objName: " + this.name
+ "<br />New objName: " + name + "<br />");
};
The property is named objName, and that name variable is obviously undefined. Did you want to have it as a parameter?
You could pass, the old and the new name to doOnSetName (Fiddle):
var MyObj = function (name) {
var that = this;
MyObj.myObjs = (MyObj.myObjs || []),
this.objName = name,
this.objIdx = MyObj.myObjs.length;
MyObj.myObjs.push(this.objName);
this.doOnSetName = function (oldName, newName) {};
this.setName = function (name) {
that.doOnNameSet(that.objName, name);
that.objName = name;
MyObj.myObjs[that.objIdx] = name;
}
}
var obj1 = new MyObj("obj1");
//obj1.doOnNameSet = function() { alert("objName: "+this.objName) };
//obj1.setName("obj1");
var obj2 = new MyObj("obj2");
obj2.doOnNameSet = function (oldName, newName) {
$("#console").append("Old objName: " + oldName
+ "<br />New objName: " + newName + "<br />")
};
obj2.setName("obj2 - changed");
$("#console ").append("Objects: <br />*" + MyObj.myObjs.join(", <br />*"));
The errors are in your obj2.doOnNameSet method. this.name should be this.objName. name is undefined in your code snippet but presumably it is defined as 'result' somewhere else in your code. You can fix this with the following change
obj2.doOnNameSet = function (name) {
Finally you need to call doOnNameSet before you make the change:
this.setName = function (name) {
that.doOnNameSet(name);
that.objName = name;
MyObj.myObjs[that.objIdx] = name;
}
Not sure what it is you're trying to do but the following will set "this" name on creation and save it in a shared names list (not a global variable like your code but a prototype property shared by all instances). When setName is used than the name in the array is set to the changed name:
var MyObj = function (name) {
this.namesIndex=this.names.length;
this.names.push(name);
this.objName = name;
}
MyObj.prototype.names=[];
MyObj.prototype.setName = function (name){
this.objName=name;
this.names[this.namesIndex]=name;
}
var o1=new MyObj(1);
var o2=new MyObj(2);
o2.setName("2 changed");
console.log(o2.names);

Categories