Методы, циклы и ключевое слово `this` - PullRequest
0 голосов
/ 30 мая 2019

Я новичок в 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'Приветствие должно вернуться: «Привет, меня зовут Лиза»

Ответы [ 3 ]

1 голос
/ 30 мая 2019

Проблема в том, что ваша локальная переменная имеет то же имя, что и параметр функции. Вы должны добавить метод к существующей переменной, а не создавать новую переменную. В инструкциях конкретно сказано: «НЕ создавайте новый объект», но это то, что вы сделали.

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);
1 голос
/ 30 мая 2019
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());
}

Чтобы решить вашу проблему, - объявите блок let userObj = { ... } вне функции "exercTwo" и передайте его как переменную

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
0 голосов
/ 30 мая 2019

Как сказано в упражнении, вам нужно только добавить функцию приветствия к объекту users. Как это:

let userObj = { name: "Lisa" };

function exercise2(userObj) {
    userObj.greetings = function () {
        return "Hi, my name is " + this.name;
    }
}

exercise2(userObj);

console.log(userObj.greetings());
...