如何命名一个新方法并使其通过函数?

时间:2019-03-05 19:24:29

标签: javascript

      var getInitials = .charAt(0).toUpperCase() 

      function Person(firstName, lastName) {
      firstName.getInitials + lastName.getInitials
        }
      Person(tom,smith);


       //const johnDoe = new Person('john', 'doe');
       //console.log(johnDoe.getInitials(), '<-- should be "JD"');

在Person的原型中添加一个名为“ getInitials”的方法,该方法返回其名字和姓氏的首字母(均大写)。不知道我在做什么错吗?语法错误?

2 个答案:

答案 0 :(得分:1)

// define a person constructor
function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}
   
// create a method on its prototype
Person.prototype.getInitials = function() {
  //  Rudimentary way of doing it. Add checks
  return this.firstName[0].toUpperCase() + this.lastName[0].toUpperCase()
};

const johnDoe = new Person('tom', 'smith');
console.log(johnDoe.getInitials());

答案 1 :(得分:0)

您的代码中有多个问题。

首先,var getInitials = .charAt(0).toUpperCase()不是有效的JS。如果要向String添加方法,则应将其添加到原型:

String.prototype.yourCustomStringFunction = function() {
    //insert your code here
}

第二,您的Person函数应返回一个值:

function Person(firstName, lastName) {
    return firstName.getInitials() + lastName.getInitials();
}

最后,使用引号(“”)定义字符串。因此,当您遇到所有这些问题时,最终的代码是:

String.prototype.getInitials = function(str) {
  return this.charAt(0).toUpperCase();
}


function Person(firstName, lastName) {
  return firstName.getInitials() + lastName.getInitials();   
}

console.log(Person("John", "Doe"));