I am new at Javascript. I am currently looking at the keyword this and methods and how to return strings.
I am struggling to return a string using the keyword this.
I have successfully created code that returns the string, but the problem is that it shows the error that "the object is already defined".
Here is the exercise I am working on and also the code I have tried to create which fails to return the correct results:
function exerciseTwo(userObj) {
// Exercise Two: You will be given an object called 'userObj'
// userObject will already have a key on it called 'name'
// Add a method to userObj, called 'greeting'.
// Using the keyword 'this', the greeting method should return the following string:
// 'Hi, my name is ' and the users name.
// eg: If userObj has a name: 'Dan', greeting should return: Hi, my name is Dan'
// NOTE: DO NOT create a new object.
// NOTE: DO NOT create a key called name the key is already on the object.
let userObj = {
name: "Lisa",
greeting: function() {
return "Hi, my name is " + this.name;
},
};
console.log(userObj.greeting());
}
//In the first line of code it shows a error which says that "userObj" is already defined. So I do not know how to return the string without creating a new object and creating a key called name.
//Here is another option I tried but it also did not work out:
function greeting() {
this.name = "Lisa";
let result = "Hi, my name is " + this.name;
return result;
},
userObj.greeting();
}
//The exercise should add a greeting method to userObject object.
So if userObj has a name: 'Lisa', greeting should return: 'Hi, my name is Lisa'
The problem is that your local variable has the same name as the function parameter. You're supposed to add a method to the existing variable, not create a new variable. The instructions specifically say "DO NOT create a new object", yet that is what you did.
function exerciseTwo(userObj) {
// Exercise Two: You will be given an object called 'userObj'
// userObject will already have a key on it called 'name'
// Add a method to userObj, called 'greeting'.
// Using the keyword 'this', the greeting method should return the following string:
// 'Hi, my name is ' and the users name.
// eg: If userObj has a name: 'Dan', greeting should return: Hi, my name is Dan'
// NOTE: DO NOT create a new object.
// NOTE: DO NOT create a key called name the key is already on the object.
userObj.greeting = function() {
return "Hi, my name is " + this.name;
};
console.log(userObj.greeting());
}
let obj = {
name: "Joe"
};
exerciseTwo(obj);
function exerciseTwo(userObj){ // The argument for this "exerciseTwo" function has been declared as "userObj"
let userObj = { // Here you are trying to declare another variable "userObj"
name: "Lisa",
greeting: function() {
return "Hi, my name is " + this.name;
}
};
console.log(userObj.greeting());
}
To solve your issue,
- Declare the let userObj = { ... } block outside the "exerciseTwo" function and pass it in as a variable
let lisa = {
name: "Lisa"
};
function exerciseTwo(userObj){ // Whatever variable you pass into this function will be synonymous to `userObj` within this function
userObj.greeting = function () {
return "Hi, my name is " + this.name;
}
console.log(userObj.greeting());
}
exerciseTwo(lisa) // lisa will take the position of `userObj` above
As the exercise says you only have to add the greeting function to the users object. Like this:
let userObj = { name: "Lisa" };
function exercise2(userObj) {
userObj.greetings = function () {
return "Hi, my name is " + this.name;
}
}
exercise2(userObj);
console.log(userObj.greetings());
Related
The above exercise was created to be completed by my teacher and I keep getting error when I ran it.
function exerciseOne() {
// Exercise One: In this exercise you will create a variable called 'aboutMe'
// This variable should be assigned a new object
// In this object create three key:value pairs
// The keys should be: 'name', 'city', 'favoriteAnimal'
// The values should be strings associated with the keys.
// return the variable 'aboutMe'
let aboutMe = {
name: 'Adebola Adesina',
city: 'Los Angeles',
favoriteAnimal: 'Zebra'
};
return aboutMe;
}
function exerciseTwo(animal) {
// Exercise Two: In this exercise you will be given an object called 'animal'
// Create a new variable called 'animalName'
// Accessing the animal object, assign the 'animalName' variable to the 'latinName' key on the object.
// return the animalName variable.
animalName = animal.latinName;
}
return animalName;
function exerciseThree(userObject) {
// Exercise Three: In this exercise you will be given an object called 'userObject'
// The phonne number for this user is incorrect!
// reassign the 'phoneNumber' key to the value: '(951)867-5309'
// return the userObject
userObject.phoneNumber = '(951)867-5309';
}
return userObject;
The above exercise was created to be completed by my teacher and I keep getting error when I ran it.
function exerciseTwo(animal) {
animalName = animal.latinName;
return animalName;
}
function exerciseThree(userObject) {
userObject.phoneNumber = '(951)867-5309';
return userObject;
}
You have to return the variables inside the function. Read about scope in javascript and differences between var and let. Also, read the error carefully and debug in browser using breakpoints and you will understand where the code is breaking.
So I created the greeting method, but I am having trouble trying to return the string with the this method. All help would be greatly appreciated please.
function exerciseTwo(userObj){
// Exercise Two: You will be given an object called 'userObj'
// userObject will already have a key on it called 'name'
// Add a method to userObj, called 'greeting'.
// Using the keyword 'this', the greeting method should return the following string:
// 'Hi, my name is ' and the users name.
// eg: If userObj has a name: 'Dan', greeting should return: Hi, my name is Dan'
// NOTE: DO NOT create a new object.
// NOTE: DO NOT create a key called name the key is already on the object.
userObj.greeting = 'Hi, my name is ' + this.name;
return userObj;
}
If you run the function without creating any new objects and call the function, this will have the scope of where you call the function from, which will be window, so you can either create a var name with the value 'users name' or set a property on window directly with window.name = 'users name';
this in JavaScript is a bit loopy.
var name = 'Dan';
console.log(window.name);
function exerciseTwo(userObj){
userObj.greeting = 'Hi, my name is ' + this.name;
return userObj;
}
console.log(exerciseTwo({}));
In the browser DOM you have a window object that is the namespace for everything the page does, so calling exerciseTwo when you are not in an object, this will resolve to window. All variables you create without a namespace will be attached to the window object.
var userObj = { // An object with the name property as Dan
name: 'Dan'
}
userObj.greeting = function () { // Adding a function to the object called greeting
return 'Hi, my name is ' + this.name;
}
console.log(userObj.greeting());
In this instance, when the function is called this has the scope of the object userObj.
Let say a I have an object:
var person= {
firstName:"Renzo",
getFirstName:function(){
console.log(this);// is the person object
return this.firstName;
},
address:{
number:function(){
console.log(this);// is the number function
//return person.getFirstName(); // it is working
return this.firstName;// not working
}
}
};
console.log(person.getFirstName());
console.log(person.address.number());
I know that "this" in the getFirstName method will reference to the person object, but "this" in the number method will not reference to the person object will reference to the number function.., I can access the getFirstName method from number function referencing to the person object, that will solve the problem but...
Question:
Is there way to reference the person object from the number method? without using the person variable... is there some special keyword like "this", to access the person method??
Another way you could do this is during the call itself:
var person = {
firstName: 'Renzo',
getFirstName() {
return this.firstName;
},
address: {
number: function() {
return this.firstName;
}
}
}
// then call it
person.address.number.call(person); // 'Renzo'
You can use ES6 classes and arrow functions to be able to achieve this.
class Person {
constructor() {
this.firstName = "Renzo";
this.address = {
getNumber: () => this.firstName
}
}
getFirstName() {
return this.firstName;
}
}
var person = new Person();
console.log(person.address.getNumber());
Here is a working fiddle - https://jsfiddle.net/sgsvenkatesh/qtg1s2f2/1/
If you are looking for a reserved keyword for accessing the grand parent, there is no such thing. You will need to tweak your code to be able to do it.
You could construct the address, so that it has access to its parent object:
function Person(n){
this.firstName=n;
this.address=new Adress(this);
}
Person.prototype= {
firstName:"Renzo",
getFirstName:function(){
console.log(this);// is the person object
return this.firstName;
}
};
function Address(p){
this.parent=p;
}
Address.prototype={
number:function(){
console.log(this);// is the number
console.log(this.parent);//the parent
return this.parent.getFirstName(); // it is working
}
};
Usecase:
console.log((new Person("Me")).address.number());
You can use it like this
var person= {
firstName:"Renzo",
getFirstName:function(){
return this.firstName;
},
address:{
number:function(){
return person.firstName;
}
}
};
console.log(person.address.number());
I am defining an object literal in JavaScript, but when I try to create a property that is a called function, I get a Uncaught ReferenceError: xxx is not defined error.
Here's an example:
var person = {
name : 'Saucy Jack',
convenienceHook : this.getName('some predefined string'),
getName : function(string) {
console.log(this.name + string);
}
};
This errors saying Uncaught ReferenceError: convenienceHook is not defined.
Nor does it work if I assign the property outside the object definition:
var person = {
name : 'Saucy Jack',
getName : function(string) {
console.log(this.name + string);
}
};
person.convenienceHook = person.getName('some predefined string');
person.convenienceHook(); //returns error
What am I missing?
Here:
var person = {
name : 'Saucy Jack',
convenienceHook : getname('some predefined string'),
getName : function(string) {
console.log(this.name + string);
}
};
you’re calling a function called getname that doesn’t exist. getName is not a property on person yet, because getname('some predefined string') has to be evaluated before the object can exist, since it’s part of the object literal. Even if it did exist, though, you still wouldn’t be able to call it as a bare getname, and even if it did, you would have to capitalize getName properly.
Your second approach also just calls person.getName. It looks like you want to make another function that will call getName:
var person = {
name : 'Saucy Jack',
convenienceHook : function() {
return this.getName('some predefined string');
},
getName : function(string) {
console.log(this.name + string);
}
};
What you assigning is not a function, you need for example to return a function from the getName function, so the convenienceHook will be a function:
getName : function() {
return function() {
console.log(this.name);
};
}
The reason your first attempt fails is that this is not person, it's whatever this is in your current scope. could be global, or could be something else if that code is within a function.
This should work
var person = {
name: "Saucy Jack",
convenienceHook: function() { return this.getName("Predefined text") },
getName: function(string) {
string=string||"";
return this.name + string; }
}
var name = 'Mike';
var person = {
name: 'John',
welcome: function(){
var name = 'Mary';
return 'Hi ' + this.name;
}
}
//person.welcome();
// output is
// Hi John
// I was expecting output to be
// Hi Mary
person.welcome.call();
// output is
// Hi Mike
// In this case since no argument is passed to call so this is window and
// I get that window.name is Mike
var name = 'Mike';
var person = {
name: 'John',
welcome: function(){
var name = 'Mary';
return 'Hi ' + this.name;
}
}
this.name refers to the object property "name"
name refers to the variable "name"
You would get the expected result with return 'Hi ' + name;
Why were you expecting Hi Mary in the first case?
var name = 'Mary';
Doesn't overwrite this.name, but rather creates a local variable named name in the function.
In the second case, you are using call, which takes a this argument, and:
Determines the value of this inside
fun. If thisArg is null or undefined,
this will be the global object.
From here.
this always refers to the object you are calling the function from. In most simple cases this would be whatever is in front of the .. For example, in the case of person.welcome() this now refers to person. If you call person.welcome.call() this refers to the window, because you did not specify anything as a parameter to call().
If you are waiting the output to be Hi Mary then you do not need to use this in the welcome function. This should do it:
var name = 'Mike';
var person = {
name: 'John',
welcome: function(){
var name = 'Mary';
return 'Hi ' + name;
}
}
When you do person.welcome() the this keyword references person, so on the welcome function this.name would become person.name which is John.