首页 > 解决方案 > 如何命名一个新方法并让它通过一个函数?

问题描述

      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”的方法,该方法返回他们的名字和姓氏的第一个字母,都大写。不知道我在这里做错了什么?语法错误?

标签: javascript

解决方案


// 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());


推荐阅读