Why isn't this anonymous function returning? - javascript

I know this is complete purposeless code I'm just experimenting with anonymous functions with code I have already written and had at hand. I can't figure out though why it array isn't returning?
(function() {
function Employee(name, age, pay) {
this.name = name;
this.age = age;
this.pay = pay || 800;
}
function Manager(name, age, pay) {
Employee.call(this, name, age, pay);
this.reports = [];
}
Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.addReport = function(report) {
this.reports.push(report);
}
function Cashier(name, age, pay) {
Employee.call(this, name, age, pay);
}
Cashier.prototype = Object.create(Employee.prototype);
var ary = [Cashier, Manager];
return ary;
}());

...why it array isn't returning?
It is. You're just not doing anything with that return value; see *** comment on first line:
var result = (function() { // ****
function Employee(name, age, pay) {
this.name = name;
this.age = age;
this.pay = pay || 800;
}
function Manager(name, age, pay) {
Employee.call(this, name, age, pay);
this.reports = [];
}
Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.addReport = function(report) {
this.reports.push(report);
}
function Cashier(name, age, pay) {
Employee.call(this, name, age, pay);
}
Cashier.prototype = Object.create(Employee.prototype);
var ary = [Cashier, Manager];
return ary;
}());
console.log(result);

Actually, this code is returning two constructor function objects. Try running it on your console :-

Related

How to store a complex object javascript

I have a complex object of this type:
class Person {
constructor(name, age, country) {
this.name = name;
this.age = age;
this.country = country;
}
setName(name) {
if (name !== null) this.name = name;
}
setAge(age) {
if (age !== null) this.age = age;
}
setCountry(country) {
if (country !== null) this.country = country;
}
getName() {
return this.name;
}
// ...
}
let person = new Person('Paul', 27, 'Haïti'); // needs to save this Object
console.log(person);
So I would like to know if anyone has an idea on how I can store this Object so that I can access it the next time I open the browser. localStorage doesn't work.
localStorage does work - you just need to use it properly
I added a toJSON method on the class - this returns an array with the constructor parameter values in the right order
class Person {
constructor(name, age, country) {
this.name = name;
this.age = age;
this.country = country;
}
toJSON() {
return [this.name, this.age, this.country];
}
setName(name) {
if (name !== null) this.name = name;
}
setAge(age) {
if (age !== null) this.age = age;
}
setCountry(country) {
if (country !== null) this.country = country;
}
getName() {
return this.name;
}
}
To save
const person = new Person("John", 23, "Aussie");
localStorage.setItem('test', JSON.stringify(person));
To load
const revivedPerson = new Person(...JSON.parse(localStorage.getItem('test')));
You don't have to make the toJSON method, but it makes for simple code (if you never need to JSON.stringify an instance of Person)
I'd add a static method to the class, that can take a plain object and return an instance of the class in return. You can use Object.create and Object.assign for that.
Demo:
class Person {
constructor(name, age, country) {
this.name = name;
this.age = age;
this.country = country;
}
static from(obj) {
return Object.assign(Object.create(this.prototype), obj);
}
getName() {
return this.name;
}
// ...
}
// Demo
let person = new Person('Paul', 27, 'Haïti');
let serialised = JSON.stringify(person);
// ... write/read serialised to/from localStorage ...
// and then:
let person2 = Person.from(JSON.parse(serialised));
console.log(person2.getName());

JavaScript OOP: Uncaught TypeError: is not a function

Have trouble with object creation. Console says that something wrong in the last line. Please tell how it should be, I more familar with Java, so this is little bit confusing for me.
var dog = {
name:"Dog",
age:"11",
getName : function() {
alert(this.name);
}
}
function Dog(name, age) {
this.name = name;
this.age = age;
}
var d1 = new Dog("Rex", 8);
d1.getName();
Your dog is just a simple Object literal,
that means that your getName is bound to it, not to your Dog class.
You can make that function a method of Dog instead:
/*var dog = {
name:"Dog",
age:"11",
getName : function() {
alert(this.name);
}
}*/
function Dog(name, age) {
this.name = name;
this.age = age;
}
Dog.prototype.getName = function() {
console.log( this.name );
}
var d1 = new Dog("Rex", 8);
d1.getName(); // "Rex"
Here's a variant that uses your settings "defaults"
function Dog() {
this.name = "Dog"; // Default name
this.age = 11; // Default age
}
Dog.prototype.getName = function() {
console.log( this.name );
}
var d1 = new Dog();
d1.name = "Rex"; // Override default name
d1.getName(); // "Rex"
You can use class with syntaxic sugar to properly create objects in ES6.
In your exemple that would write like this :
'use strict';
class Dog{
constructor(name, age){
this.name = name;
this.age = age;
}
getName(){
console.log(this.name);
}
}
let doggy = new Dog("krypto", 125);
doggy.getName();
Traditional OO in JavaScript
function Dog(name, age) {
this.name = name || "Dog";// if the name is not given, it defaults to "Dog"
this.age = age || "11";
}
Dog.prototype.getName = function() {
alert(this.name);
}
var d1 = new Dog("Rex", 8);
d1.getName();
More Explicit OO in JavaScript
function createDog(name, age) {
// create a new dog and return it
var dog = {
name: name || "Dog",// if the name is not given, it defaults to "Dog"
age: age || "11"
};
return dog;
}
createDog.getName = function(dog) {
// explicit dog as 1st parameter
alert(dog.name);
}
//createDog is a normal function that returns something, no "new" needed
var d1 = createDog("Rex", 8);
createDog.getName(d1);

javascript using a object method into another object

im trying to make 2 objects from my 2 classes, a Person object and a Drink object, then i want to call my drinking method passing a Drink objectbut i dont know how, how can i do that? here is my code, i cant see why it is not working
function Drink(full, alcoholic){
this.alcoholic = alcoholic;
this.full = full;
}
function Person(name, age) {
this.name = name;
this.age = age;
this.drinking = function drinking(Drink) {
if (age >= 18) {
this.Drink.full = false;
} else {
console.log("you cannot drink because of your age")
this.Drink.full=true;
};
}
}
John = new Person("John",24);
Sam = new Person("Sam",2);
x = new Drink(true,true);
console.log(x)
console.log(John.drinking(x))
console.log(Sam.drinking(x))
Remove this on this.Drink
function Drink(full,alcoholic){
this.alcoholic = alcoholic;
this.full = full;
}
function Person(name,age){
this.name = name;
this.age = age;
this.drinking= function drinking(drink) {
if (age>=18) {
drink.full=false;
} else {
console.log("no puede tomar")
drink.full=true;
};
}
}
John = new Person("John",24);
Sam = new Person("Sam",2);
x = new Drink(true,true);
console.log(x)
console.log(John.drinking(x))
console.log(Sam.drinking(x))

Javascript - What is the difference between these constructor functions?

What is the difference between this constructor function:
var Person = function(living, age, gender) {
this.living = living;
this.age = age;
this.gender = gender;
this.getGender = function() {return this.gender};
}
and this one:
var Person = function Person(living, age, gender) {
this.living = living;
this.age = age;
this.gender = gender;
this.getGender = function() {return this.gender;};
};
Nothing at all, other than the constructor function being "named". For #1, Person.name would evaluate to an empty string, and for #2, Person.name would evaluate to "Person".
The name property will be set in the function Person(...).
You can see this by trying something like
var bar = function eigor(){}
and then seeing what bar.name is.

How do you put an if/else statement inside an object key?

I'm trying to create a Person class. The person's age would be a random number, determined by an if/else statement. Right now it seems to only work if I place the function outside of the object, or as a separate key.
function age(x) {
if (x.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) {
return Math.floor(Math.random()*40+1);
}
else {
return Math.floor(Math.random()*40+41);
}
}
function person(name) {
this.name = name;
this.age = age(name);
}
var people = {
joe: new person("Joe")
};
console.log(people.joe.age);
\\ returns a number 41-80
Is there a way for me to put the function directly into the "this.age" key and have the same thing happen, like so:
function person(name) {
this.name = name;
this.age = function age() {
if (this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) {
return Math.floor(Math.random()*40+1);
}
else {
return Math.floor(Math.random()*40+41);
}
};
You can execute the function immediately:
function person(name) {
this.name = name;
this.age = (function age() {
if (this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) {
return Math.floor(Math.random()*40+1);
}
else {
return Math.floor(Math.random()*40+41);
}
})();
};
function person(name) {
this.name = name;
this.age = (function age() {
var x = this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0))?1:41;
return Math.floor(Math.random()*40+x);
})();
};
doing (function(){})() you're executing it.
(function(){}) //this converts the function into a statement
() // this executes
You have to define the closure (function) and execute it right on.
function person(name) {
this.name = name;
this.age = (function age() {
var x = this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) ? 1 : 41;
return Math.floor(Math.random()*40+x);
})();
};

Categories

Resources