Я новичок в Javascript.В настоящее время я смотрю на ключевое слово this
и методы и как вернуть строки.Я пытаюсь вернуть строку, используя ключевое слово this
.
Я успешно создал код, который возвращает строку, но проблема в том, что он показывает ошибку, что «объект уже определен».
Вот упражнение, над которым я работаю, а также код, который я пытался создать, который не может вернуть правильные результаты:
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.
Так что, если userObj имеет имя: 'Lisa'Приветствие должно вернуться: «Привет, меня зовут Лиза»