I am trying to build a function that creates a person by receiving at first a full name and using methods to set the first, last and full name. Afterwards it would have methods that should be able to change each part of the name.
My current code looks like this:
var Person = function(firstAndLast) {
var name = firstAndLast;
this.getFirstName = function() {
return name.substr(0,name.indexOf(' '));
};
this.getLastName = function() {
return name.substr(name.indexOf(' ')+1);
};
this.getFullName = function() {
return name;
};
this.setFirstName = function() {
return name;
};
this.setLastName = function() {
return name;
};
this.setFullName = function() {
return name;
};
};
var bob = new Person('Bob Ross');
bob.setFullName();
Now I am completely stuck when it gets time to pass a new name, so that if I do something like:
bob.setFullName('George Carlin');
and then pass:
bob.getFullName();
I should get the answer 'George Carlin'.
yet this isn't happening.
Thanks as always.
So the problem was that I wasn't really understanding how the values where being passed, and that instead of working on a full name I should be working on the parts.
var Person = function(firstAndLast) {
var firstName = firstAndLast.split(' ')[0];
var lastName = firstAndLast.split(' ')[1];
this.setFirstName = function(firstNameNew) {
firstName = firstNameNew;
};
this.setLastName = function(lastNameNew) {
lastName = lastNameNew;
};
this.setFullName = function (fullNameNew) {
firstName = fullNameNew.split(' ')[0];
lastName = fullNameNew.split(' ')[1];
};
this.getFullName = function() {
return firstName + ' ' + lastName;
};
this.getFirstName = function() {
return firstName;
};
this.getLastName = function() {
return lastName;
};
};
var bob = new Person('Bob Ross');
Related
**
I don't want to print anything instead of "undefined" if I have not entered value next to "user1" (course count) in new user like : ("user1",2)
var User = function(firstName,courseCount){
this.firstName = firstName;
this.courseCount = courseCount;
this.getCourseCount = function(){
console.log(`Course count is: ${this.courseCount}`);
};
};
User.prototype.getFirstName = function () {
console.log(`User Name is : ${this.firstName}`);
};
var user1 = new User("user1",);
if (user1.hasOwnProperty("firstName")) {
user1.getFirstName();
}
if (user1.hasOwnProperty("getCourseCount")) {
user1.getCourseCount();
};
if (user1.hasOwnProperty("getCourseCount")) {
user1.getCourseCount();
};**
var User = function(firstName,courseCount){
this.firstName = firstName;
this.courseCount = courseCount?courseCount:'';
this.getCourseCount = function(){
console.log(`Course count is: ${this.courseCount}`);
};
};
User.prototype.getFirstName = function () {
console.log(`User Name is : ${this.firstName}`);
};
var user1 = new User("user1",);
if (user1.hasOwnProperty("firstName")) {
user1.getFirstName();
}
if (user1.hasOwnProperty("getCourseCount")) {
user1.getCourseCount();
};
var User = function(firstName,courseCount){
this.firstName = firstName;
this.courseCount = courseCount;
this.getCourseCount = function(){
if(this.courseCount===undefined){this.courseCount=""}
console.log(`Course count is: ${this.courseCount}`);
};
};
this will prevent to print undefined
I'm trying to make a basic one-page address book without a database, and I wanted to assign ids to the contacts to make them easier to find. However, when I've tried to add contacts, nothing gets assigned. Any help would be appreciated!
function AddressBook() {
this.contacts = [];
this.currentId = 0;
}
AddressBook.prototype.addContact = function(contact) {
contact.id = this.assignID;
this.contacts.push(contact);
}
AddressBook.prototype.assignID = function() {
this.currentID += 1;
return this.currentId;
}
AddressBook.prototype.findContact = function(id) {
for (let i = 0; i < this.contacts.length; i++) {
if(this.contacts[i].id == id) { //uses loose equality to leave room for input error
return this.contacts[i];
}
};
return false;
}
function Contact(firstName, lastName, phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
}
Contact.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
}
In addition to calling assignId note that you have uppercase D in this.currentID += 1 but lowercase d in the line below that and in the constructor so you should make the uppercase D lowercase
You have defined assignID as a method, but you've used as a property.
To your code works, you need change addContact method like the below code:
AddressBook.prototype.addContact = function(contact) {
contact.id = this.assignID(); //<===== calling like a method not a property
this.contacts.push(contact);
}
However, note that currentId is a property of one instance. So, you code will ever put 1 to all IDs.
To fix it, you can change currentId to be one class property like this:
AddressBook.currentId
And in all places reference this property with the class name before:
AddressBook.prototype.assignID = function() {
AddressBook.currentId += 1; //<====== note that in your code you use ID as upper case, different that you have defined it
return AddressBook.currentId;
}
Using currentId as a class property, all instances of the class will share this property and each call for assignID() will update the shared property and make that the next instance of the class gets one new ID.
The final code should looks like:
function AddressBook() {
this.contacts = [];
}
AddressBook.currentId = 0;
AddressBook.prototype.addContact = function(contact) {
contact.id = this.assignID();
this.contacts.push(contact);
}
AddressBook.prototype.assignID = function() {
return ++AddressBook.currentId; //here, first currentId is incremented and after it is returned
}
AddressBook.prototype.findContact = function(id) {
for (let i = 0; i < this.contacts.length; i++) {
if(this.contacts[i].id == id) { //uses loose equality to leave room for input error
return this.contacts[i];
}
};
return false;
}
function Contact(firstName, lastName, phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
}
Contact.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
}
Working on a Javascript lesson and I'm stuck trying to figure out how to answer/understand how to complete this question wanted to know if anyone could help.
function Container(param) {
var person = {
firstName: 'Jimmy',
lastName: 'Smith',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName (name) {
var words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
}
}
// Attempting to clone private getter don't know how to access it.
function objectClone(person) {
var orginal = person //Trying to access the private method
var clone = function cloneObj { Object.assign({}, original); }
clone.prototype.spillSecret = function() { alert(this.getfullName()); }
;}
Use Object.assign to copy the normal properties, and then copy the special properties by hand after:
copy = Object.assign({}, original);
copy.year = original.year;
But this doesn't use a closure anywhere, so I'm not sure if it's what your tutorial is looking for.
var Person = function(person){
var name = 'John Doe';
function copy(){
var newPerson = Object.assign({}, person);
Object.defineProperty(newPerson, 'name', {
get: function() { return name; },
set: function(newName){ if(typeof newName !== 'string') {console.error('invalid name')} else name = newName},
enumerable: true,
configurable: true
});
return newPerson;
}
return copy();
};
var person1 = {
age: 20,
location: 'India'
}
var person2 = Person(person1);
var person3 = Person(person1);
person3.name = 1234; // invalid name
person3.name = 'Mr. India';
console.log(person1.name); // undefined
console.log(person2.name); // John Doe
console.log(person3.name); // Mr. India
I am wondering why when I make adjustments to the following code:
var product = {
firstname: "john",
lastname: "kcarl",
fullname : function() { return this.firstname + " " + this.lastname }
};
function write()
{
document.write(product.fullname());
};
write();
**** the following fullname becomes undefined
function write(method)
{
document.write(product.method());
};
write(fullname);
**** even when I try this it comes undefined
function write(method)
{
document.write(method());
};
write(product.fullname);
It's because of scope issue with javascript. Here is a better way to write this code:
var Product = function() {
var self = this;
this.firstname = "john";
this.lastname = "kcarl";
this.fullname = function() {
return self.firstname + " " + self.lastname;
}
};
var product = new Product();
var fullnameMethod = product.fullname;
document.write(fullnameMethod());
In the above example, I save the scope into a variable called self and I can feel free to call the fullname() method anytime
I want to be able to assign default values to variables when I'm using prototyping for object creation.
When I try to assign default values to the variables they are always 'undefined'.
I have tried to find the answer but all the possible solutions I have tried dont work.
My questions are:
why do a variable that have I have initiated with a value has the value 'undefined'
how do I solve my problem?
(function() {
EmployeeNS = {};
EmployeeNS.Employee = function() {
var _firstName;
var _lastName;
var _employeeID = 'Unassigned';
}
EmployeeNS.Employee.prototype.setFirstName = function(fName) { this._firstName = fName; };
EmployeeNS.Employee.prototype.getFirstName = function() { return this._firstName; };
EmployeeNS.Employee.prototype.setLastName = function(lName) { this._lastName = lName; };
EmployeeNS.Employee.prototype.getLastName = function() { return this._lastName; };
EmployeeNS.Employee.prototype.setEmployeeID = function(employeeID) { this._employeeID = employeeID; };
EmployeeNS.Employee.prototype.getEmployeeID = function() { return this._employeeID; };
EmployeeNS.Worker = function() {
var _department;
}
EmployeeNS.Worker.prototype = new EmployeeNS.Employee();
EmployeeNS.Worker.prototype.constructor = Worker;
EmployeeNS.Worker.prototype.setDepartment = function(department) { this._department = department; };
EmployeeNS.Worker.prototype.getDepartment = function() { return this._department; };
})();
function createWorker() {
var x = new EmployeeNS.Worker();
x.setFirstName("John");
x.setLastName("Doe");
x.setDepartment("Transport");
var message = x.getFirstName()
+ " "
+ x.getLastName()
+ " (Department: "
+ x.getDepartment()
+ " / EmployeeID: "
+ x.getEmployeeID()
+ ")";
alert(message);
}
Thanks
you can simply make it to work by changing like this,
EmployeeNS.Employee = function() {
this._firstName;
this._lastName;
this._employeeID = 'Unassigned';
}
Try out this way , you can make those variables truly private by wrapping Employee ,
(function() {
EmployeeNS = {};
(function() {
var _firstName;
var _lastName;
var _employeeID = 'Unassigned';
EmployeeNS.Employee = function() {
}
EmployeeNS.Employee.prototype.setFirstName = function(fName) { _firstName = fName; };
EmployeeNS.Employee.prototype.getFirstName = function() { return _firstName; };
EmployeeNS.Employee.prototype.setLastName = function(lName) { _lastName = lName; };
EmployeeNS.Employee.prototype.getLastName = function() { return _lastName; };
EmployeeNS.Employee.prototype.setEmployeeID = function(employeeID) { _employeeID = employeeID; };
EmployeeNS.Employee.prototype.getEmployeeID = function() { return _employeeID; };
})();
(function() {
var _department;
EmployeeNS.Worker = function() {
}
EmployeeNS.Worker.prototype = new EmployeeNS.Employee();
EmployeeNS.Worker.prototype.constructor = Worker;
EmployeeNS.Worker.prototype.setDepartment = function(department) { _department = department; };
EmployeeNS.Worker.prototype.getDepartment = function() { return _department; };
})();
})();
Here is the jsfiddle
If you want instance properties, do it like this:
(function() {
EmployeeNS = {};
EmployeeNS.Employee = function () {
this._firstName = null;
this._lastName = null;
this._employeeID = 'Unassigned';
};
EmployeeNS.Employee.prototype.setFirstName = function(fName) {
this._firstName = fName;
};
})();