Unable to call a method defined inside an object in javascript - javascript

i have defined an object containing an array of objects and functions and called the methods as below:
var Person = {
people: [{
name: "Max",
age: 41,
},
{
name: "John",
age: 25,
},
{
name: "Doe",
age: 67,
},
],
greeting: function() {
return "Hello, my name is" + " " + this.name;
}
};
function searchByName(namePerson) {
var result = Person.people.find(Obj => Obj.name === namePerson);
return result;
}
var max = searchByName('Max');
max.greeting();
Is something wrong with my function definition? On running it says "greeting" is not a function.

You could change your Person into an actual class that you could instantiate with new Person()
//make the person class
function Person ( person ) {
this.name = person.name;
this.age = person.age;
}
//add the greeting method to the person class
Person.prototype.greeting = function () {
return "Hello, my name is" + " " + this.name;
};
//build your people
var people = [
new Person( { name: "Max", age: 41 } ),
new Person( { name: "John", age: 25 } ),
new Person( { name: "Doe", age: 67 } )
];
function searchByName(namePerson) {
var result = people.find(person => person.name === namePerson);
return result;
}
var max = searchByName('Max');
console.log( max.greeting() );

Your code doesn't make much sense, your greeting function is on the outer Person object but you are using it as if it were a property of each person inside the array.
You need a constructor for persons so you can instantiate three Persons with a greeting method
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greeting = function() {
return "Hello, my name is " + this.name + " and I am " + this.age + " years old";
}
const people = [
new Person("Max", 41),
new Person("JOhn", 25),
new Person("Doe", 67),
];
function searchByName(namePerson) {
var result = people.find(obj => obj.name === namePerson);
return result;
}
var max = searchByName('Max');
console.log(max.greeting());

You're returning an object, which does not have a greeting function.
A potential different solution with a little bit of a different structure is this.
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greeting = function() {
return "Hello, my name is " + this.name;
}
function People(personArr) {
this.people = personArr;
}
People.prototype.searchByName = function(name) {
return this.people.find( person => person.name === name);
}
var people = new People([new Person("Max", 41), new Person("John", 25), new Person("Doe", 67)]);
var max = people.searchByName("Max");
console.log(max.greeting());

Related

Trying to make a data module

I'm trying to make a data module in JavaScript, but can't access the data from outside, while everything works fine when I try to log it from inside
'use strict;'
function manager() {
let data = {};
function define(name, surname, age) {
let length = Object.keys(data).length;
data[`user${length + 1}`] = {
name: name,
surname: surname,
age: age
};
}
function get(num) {
return data[`user${num}`];
}
return {
define: define,
get: get
};
};
manager().define('John', 'Smith', 17);
console.log(manager().get(1));
//undefined
Every time you call manager you define a new variable named data and assign it the value {}.
So manager().define('John', 'Smith', 17); creates an object, assigns some data to it, then the object drops out of scope and is garbage collected.
Then console.log(manager().get(1)); creates a new object, and it has no data in it.
Define the variable and assign the object to it outside the function.
Kindly use module pattern and the execution will like this
var manager = (function() {
'use strict';
let data = {};
function define(name, surname, age) {
let length = Object.keys(data).length;
data[`user${length + 1}`] = {
name: name,
surname: surname,
age: age
};
}
function get(num) {
return data[`user${num}`];
}
return {
define: define,
get: get
};
}());
manager.define('John', 'Smith', 17)
console.log(manager.get(1))
var manager = (function() {
'use strict';
let data = {};
function define(name, surname, age) {
let length = Object.keys(data).length;
data[`user${length + 1}`] = {
name: name,
surname: surname,
age: age
};
}
function get(num) {
return data[`user${num}`];
}
return {
define: define,
get: get
};
}());
manager.define('John', 'Smith', 17)
console.log(manager.get(1))

How to assign JSON to a class recursively?

To modelize a family structure, I used the simple Person class, and I would be able to save a structure as text, and later go in the other way. But my class has different methods useful and indispensable to my code, I found the way for the first object, but how to continue in depth?
Depth here is 1, but it can go up to 6
let json = {"name":"SON","date":"2000-01-01T05:00:00.000Z","sex":"H",
"dad":{"name":"DAD","date":"2000-01-02T05:00:00.000Z","sex":"H","dad":null,"mom":null},
"mom":{"name":"MOM","date":"2000-01-03T05:00:00.000Z","sex":"F","dad":null,"mom":null}
};
class Person {
constructor(name, date, sexe) {
this.name = name;
this.date = date;
this.sexe = sexe;
this.dad = null;
this.mom = null;
}
doStuff(){
console.log(this.name);
}
}
let obj = Object.assign(new Person,json);
//OK
obj.doStuff();
//NOK 'obj.dad.doStuff is not a function' as 'dad' is not associated to Person
obj.dad.doStuff();
You can do it recursively, calling the same function that performs Object.assign on dad and mom if they are not null:
let json = {
"name": "SON", "date": "2000-01-01","sex": "H",
"dad": {
"name": "DAD","date": "2000-01-02","sex": "H", "dad": null,"mom": null
},
"mom": {
"name": "MOM","date": "2000-01-03","sex": "F","dad": null,
"mom" : { "name": "GRAMDA","date": "2000-01-02","sex": "F","dad": null,"mom": null }
}
};
class Person {
constructor(name, date, sexe) {
this.name = name;
this.date = date;
this.sexe = sexe;
this.dad = null;
this.mom = null;
}
doStuff() {
console.log(this.name);
}
}
function buildPersons(root) {
let obj = Object.assign(new Person, root);
if (obj.dad) obj.dad = buildPersons(obj.dad);
if (obj.mom) obj.mom = buildPersons(obj.mom);
return obj;
}
let obj = buildPersons(json);
obj.doStuff();
obj.dad.doStuff();
obj.mom.mom.doStuff();

Call React Function not working

I have code is below, I want my result is "Hello Mr. John Doe".
function formatname(name) {
return name.fullName;
};
const name = {
firstName: 'John',
lastName: 'Doe',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
const getName = (
<h1>Hello Mr. {formatname(name)}</h1>
);
ReactDOM.render(
getName,
document.getElementById('root')
);
But when I save it return is "Hello Mr. ", what I wrong in variable fullName.
In your code:
const name = {
firstName: 'John',
lastName: 'Doe',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
this is not refered to your variable name anymore. To solve, you need to bind this back to the name you declared:
formatname(name).bind(name)()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.

Adding additional functions to object literals after it has been created

So I was wondering whether this is the right way to add functions to an object created through object literals.
var person = {
firstname: "default",
lastname: "default",
greet: function () {
return "hi " + this.firstname;
}
}
var me = Object.create(person);
me.myFunction = function() {
return console.log("meow");
};
console.log(me.myFunction());
However it returns an undefined after meow, is there any reason why it would do so?
When you write
return console.log("meow");
you don't return "meow", but the return value of console.log, which is undefined. Modify the code like this:
me.myFunction = function() {
return "meow";
};
console.log(me.myFunction());
console.log() doesn't return any value, so the "fallback" value of the function is undefined.
Since you're returning the return value of console.log and log that again, you get undefined.
All of this has nothing to do with modifying an object or a prototype.
You should return meow within myFunction:
var person = {
firstname: "default",
lastname: "default",
greet: function () {
return "hi " + this.firstname;
}
}
var me = Object.create(person);
me.myFunction = function() {
return "meow";
};
document.write(me.myFunction());
var person = {
firstname: "default",
lastname: "default",
greet: function () {
return "hi " + this.firstname;
}
}
var me = Object.create(person);
me.myFunction = function() {
return console.log("meow");
};
console.log(me.myFunction());
why you return console.log() it's return nothing

Getters are not working in JavaScript

I`m trying to figure out what is getters and setters in JavaScript.
Here is my object
function User(fullName) {
this.fullName = fullName;
Object.defineProperties(this,{
firstName :{
get: function(){
return this.fullName.split(" ")[0];
},
set :function(value){
this.firstName = value;
}
},
lastName:{
get: function(){
this.lastName = this.fullName.split(" ")[1];
},
set: function(value){
this.lastName = value;
}
},
fullName :{
set: function(value){
this.fullName = value;
}
}
});
}
Then creates a new user:
var user = new User("New User");
But when I`m trying to get the firstName property like
alert( user.firstName )
it throw an error "Cannot read property 'split' of undefined".
What may cause the problem? It looks like 'this' is not visible inside get function, but as I understand it should. Thanks!
You don't need a setter for fullName as direct assignment will work.
function User(fullName) {
this.fullName = fullName || '';
Object.defineProperties(this, {
firstName: {
get: function() {
return this.fullName.split(" ")[0];
},
set: function(value) {
this.firstName = value; // NOTE: This will throw an error
}
},
lastName: {
get: function() {
return this.fullName.split(" ")[1];
},
set: function(value) {
this.lastName = value; // NOTE: This will throw an error
}
}
});
}
var joe = new User('John Doe');
var jane = new User('Jane Dane');
jane.fullName = 'Jane Doe';
document.write(
'<pre>' + joe.firstName + '</pre>' +
'<pre>' + jane.lastName + '</pre>'
);
However, as noted in the code comments above you can't set a property on this to the same name as a defined property with a setter. For example:
// defining `firstName`
firstName: {
...
set: function(value) {
this.firstName = value; // NOTE: This will throw an error
}
This operation will cause a recursion stack error as it will continuously try to update firstName since this.firstName is a setter.
To avoid this you could use local scoped variables inside the constructor function and do something like:
function User(fullName) {
var firstName;
var lastName;
Object.defineProperties(this, {
firstName: {
get: function() {
return firstName;
},
set: function(value) {
return (firstName = value);
}
},
lastName: {
get: function() {
return lastName;
},
set: function(value) {
return (lastName = value);
}
},
fullName: {
get: function() {
return firstName + ' ' + lastName;
},
set: function(value) {
var names = value && value.split(' ');
firstName = names[0];
lastName = names[1];
}
}
});
if (fullName) {
this.fullName = fullName;
}
}
var joe = new User('John Doe');
var jane = new User('Jane Dane');
jane.lastName = 'Doe';
document.write(
'<pre>' + joe.firstName + '</pre>' +
'<pre>' + jane.lastName + '</pre>'
);
Some issues/changes needed to your code:
this.fullName.split(" ")[0]; => will try to invoke the getFullName since fullName is defined as a property. Since you have not defined getFullName this results in an error
Say you go ahead and define a getter for fullName:
get: function() {
return this.fullName;
}
This will throw a stackoverflow since this.fullName ends up recursively calling getFullName()
The right way to use it would be (of course update the setters to do something useful):
function User(fullName) {
this.fullName = fullName;
Object.defineProperties(this, {
firstName: {
get: function () {
return this.fullName.split(" ")[0];
},
set: function (value) {
this.firstName = value;
}
},
lastName: {
get: function () {
return this.fullName.split(" ")[1];
},
set: function (value) {
this.lastName = value;
}
}
});
}
var user = new User("New User");
alert( user.firstName );
fullName does not have a getter so it return undefined
get
A function which serves as a getter for the property, or undefined if there is no getter. The function return will be used as the value of property.
Defaults to undefined.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Description

Categories

Resources