javascript - 这是正确的方法吗?我不想使用原型,而只是使用类构造函数上的方法
问题描述
// 向 Person 的原型添加一个名为“isLegalDriver”的方法,如果该人年满 16 岁,则返回 true。
function Person(name, age) {
this.isLegalDriver = function(){
if(age >= 16){
return true
} else {
return false
};
}
}
/* Do not modify code below this line */
const youngPerson = new Person('Jane', 15);
console.log(youngPerson.isLegalDriver(), '<-- should be false');
const olderPerson = new Person('Joan', 16);
console.log(olderPerson.isLegalDriver(), '<-- should be true');
解决方案
It's not wrong. It creates the function on the object and that function returns the correct value.
There are changes I'd make, but it's not wrong:
I'm not a fan of relying on automatic semicolon insertion, so I'd add a
;
on the end of the function assignment (and other statements, but see the next bullet point). Other people like ASI and wouldn't.Rather than using
if
/else
, I'd just return the result of the comparison.
So:
this.isLegalDriver = function() {
return age >= 16;
};
推荐阅读
- java - 如何从 java.lang.reflect.Type 创建通用列表
- rabbitmq - ZMTP 和 AMQP 协议的区别
- ruby-on-rails - 如何将语言环境变量传递给局部变量
- abp - abpframework 现在是否有类似于之前的 IUserNavigationManager 的域服务实现来获取用户导航菜单?
- symfony - Symfony - 具有不同访问控制的两条相同路线
- django - Django Rest Framework:同一模型的第二个视图集上的超链接不正确
- mysql - 经典 ASP - 连接到 PHPMyAdmin MySQL 数据库 - 可能吗?
- docker - 如何解决docker OCI运行时创建失败的启动容器进程导致“exec:\”java\“:$PATH中找不到可执行文件”:
- c++ - 将所有派生余额保存到父余额
- angular - 角材料步进器未正确显示