首页 > 解决方案 > 这是正确的方法吗?我不想使用原型,而只是使用类构造函数上的方法

问题描述

// 向 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');

标签: javascript

解决方案


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;
};

推荐阅读