Call React Function not working - javascript

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.

Related

Typescript cant access object property

I have little issue accessing object property in typscript. this works fine in js but doesn't in ts
let getUserName = {
firstname : "timi",
lastname: "oluwayomi",
middlename: "ola",
full : () => { return this.firstname + this.lastname + this.middlename } ,
first: () => { return this.firstname }
}
console.log(getUserName.first())
in javascript output: timi
but ts throws error. is there a different way to access it in ts ?
just refer to the same object in the object, this is a hack IMO
let getUserName = {
firstname : "timi",
lastname: "oluwayomi",
middlename: "ola",
full : () => { return getUserName.firstname + getUserName.lastname + getUserName.middlename } ,
first: () => { return getUserName.firstname }
}
console.log(getUserName.first())
this inside arrow function refers to the global object, so its giving error, you can try with traditional functions
let getUserName = {
firstname : "timi",
lastname: "oluwayomi",
middlename: "ola",
full : function() { return this.firstname + this.lastname + this.middlename } ,
first: function() { return this.firstname }
}
console.log(getUserName.first())
i was working on an component based project "Angular"
so i had to initialize first
getUserName : any;
getUserName = {
firstname : "timi",
lastname: "oluwayomi",
middlename: "ola",
full : () => { return getUserName.firstname + getUserName.lastname + getUserName.middlename } ,
first: () => { return getUserName.firstname }
}
console.log(getUserName.first())
also thanks to Dean Van Greunen
You are accessing this within an arrow function. Inside an arrow function, this refers to the global object, not the execution context. See You Don't Know JS Yet - Chapter 3 - this Keyword for more info on this.
So, to start with, use this:
let getUserName = {
firstname : "timi",
lastname: "oluwayomi",
middlename: "ola",
full() { return this.firstname + this.lastname + this.middlename },
first() { return this.firstname },
}
As this is of type any in this case, as the TypeScript compiler cannot infer the type of your object for you, you will need to type the object yourself (usually a good idea anyway):
type GetUserName = {
firstname: string;
lastname: string;
middlename: string;
full(): string;
first(): string;
}
let getUserName: GetUserName = {
firstname: "timi",
lastname: "oluwayomi",
middlename: "ola",
full(this: GetUserName) {
return this.firstname + this.lastname + this.middlename;
},
first(this: GetUserName) {
return this.firstname;
},
};

Passing particular argument to a function having multiple arguments in React

In React, I have created function mentioned below:
infoPrint (firstname = '--', middlename = '--', surname = '--')
{
console.log('Firstname: ', firstname, ', Middle name: ', middlename, ', Surname: ', surname);
}
I am calling this function in componentWillMount:
componentWillMount() {
var firstname = 'Naisarg';
var surname = 'Parmar';
this.infoPrint(firstname,surname);
}
I am getting this output:
Firstname: Naisarg, Middle name: Parmar, Surname: --
But I'm expecting this one:
Firstname: Naisarg, Middle name: --, Surname: Parmar
You can achieve that by passing a literal object as argument of your function:
class User extends Component {
componentWillMount() {
var firstname = 'Naisarg';
var surname = 'Parmar';
this.infoPrint({ firstname, surname });
}
infoPrint({ firstname = '--', middlename = '--', surname = '--' }) {
console.log('Firstname: ', firstname, ', Middle name: ', middlename, ', Surname: ', surname);
}
}
It's a very common pattern that helps a lot with optional parameters.
-
If you prefer not to use an object, then you must pass all the arguments in the correct order:
class User extends Component {
componentWillMount() {
var firstname = 'Naisarg';
var surname = 'Parmar';
this.infoPrint(firstname, null, surname);
}
infoPrint(firstname = '--', middlename = '--', surname = '--') {
console.log('Firstname: ', firstname, ', Middle name: ', middlename, ', Surname: ', surname);
}
}
To achieve what you require, you will either need to pass -- or null for the middlename argument:
componentWillMount() {
var firstname = 'Naisarg';
var surname = 'Parmar';
this.infoPrint(firstname, null, surname);
this.infoPrint(firstname, '--', surname);
}
or alternatively, you could refactor your method signature by passing these arguments indirectly via an object argument:
function infoPrint(name = { first: '--', middle: '--', last: '--' }) {
console.log('Firstname: ', name.first, ', Middle name: ', name.middle, ', Surname: ', name.last);
}
infoPrint({
first: 'Naisarg',
last: 'Parmar'
});
The "object argument" method shown above resolves the issue you're facing by retaining a (key) relationship between the arguments themselves, and the way in which each keyed argument is actually used in your infoPrint() function.
Without this, the JavaScript run-time has no way of knowing that you intend the surname variable to actually be passed to infoPrint() as the "third surname argument" - simply put, the arguments that you pass are assigned from first to last. Substituting the variable with values as shown below might give more insight as to what's happening, and why your original code doesn't work as expected:
// var firstname = 'Naisarg';
// var surname = 'Parmar';
// Substitute variables with values to better understand how
// arguments are being passed to the function
this.infoPrint(
'Naisarg' /* <-- firstname */,
'Parmar' /* <-- middlename */,
/* no value for surname, so use default "--" */
); /* Prints: "Firstname: Naisarg , Middle name: Parmar , Surname: -- " */

Unable to call a method defined inside an object in 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());

how to add a property to an object?

Given an object that has a "firstName" property and a "lastName" property, "addFullNameProperty" returns a "fullName" property whose value is a string with the first name and last name separated by a space.
var person = {
firstName: 'Jade',
lastName: 'Smith'
};
addFullNameProperty(person);
console.log(person.fullName); // --> 'Jade Smith'
my code :
function addFullNameProperty(obj) {
// your code here
obj[fullName] = obj.firstName + obj.lastName;
}
Just simple set:
obj.fullName instead of obj[fullName]
Or
obj['fullName']
Because fullName in your code is undefined variable. So JS alert error.
Either use obj.fullName or obj['fullName']
But a more correct solution would be
function addFullNameProperty(obj) {
// your code here
Object.defineProperty(obj, 'fullName', {
get: function(){
return this.firstName + ' ' + this.lastName;
},
configurable:false
});
}
var person = {
firstName: 'Jade',
lastName: 'Smith'
};
addFullNameProperty(person);
console.log(person.fullName); // --> 'Jade Smith'
person.firstName = "Mike";
console.log(person.fullName); // --> 'Mike Smith'
This way your object will always return the correct fullName.
If you want to add the space into the name, you will need to do string interpolation, like so:
`${obj.firstName} ${obj.lastName}`
and complement this with Gaby's answer about switching to dot notation, obj.fullName
Add new property to an existing object:
const person = {
firstName: 'Jade',
lastName: 'Smith'
};
person.fullName = `${person.firstName} ${person.lastName}`;
same as:
person['fullName'] = `${person.firstName} ${person.lastName}`;
or using method:
const person = {
firstName: 'Jade',
lastName: 'Smith',
fullName(){
return `${this.firstName} ${this.lastName}`;
}
};
person.fullName(); // Jade Smith
You can also use defineProperty
Try this
return obj.fullName = obj.firstName + " " + obj.lastName

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

Categories

Resources