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”的方法,该方法返回他们的名字和姓氏的第一个字母,都大写。不知道我在这里做错了什么?语法错误?
解决方案
// 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());
推荐阅读
- c# - 尝试在 cloud9 IDE 上运行 C# 但收到错误
- sql - 数据透视表在 SQL Server 2012 中没有得到正确的输出
- c - C程序从单独文件中的关键字文本文件中计算关键字并显示它们
- php - Docker Compose 使用域而不是本地主机
- javascript - 如何停止直到 setstate 执行本机反应?
- dialogflow-es - 操作权限 Intent 不适用于 alpha 测试人员
- scala - 将具有任何案例类返回类型的函数作为参数传递
- java - 如何在服务发现库中禁用 CompositeDiscoveryClient 和 SimpleDiscoveryClient
- django - Django:如何将 2 个表单集合并为一个,以便在模板中显示为一个内联表(当然还有分页)
- bash - 如何遍历目录和子目录并获取父目录的名称?