如何避免在Javascript中进行“字符串”输入?

时间:2017-05-31 02:19:08

标签: javascript refactoring

我一直在做一个关于干净代码的课程。该课程表明,“串”式输入是可读性的坏事,并建议使用不同的结构(课程使用C#):

//Dirty
if (employeeType == "manager") 

//Clean
if (employee.Type == EmployeeType.Manager)

我的问题是:如何在javascript中实现类似的结构?

我应该创建像这样的对象吗?

EmployeeType = {
    Manager: "manager"
}

employee = {
    Type: : "manager"
}

这是更好的方法吗?

1 个答案:

答案 0 :(得分:1)

如果您使用ES6和类,则可以使用instanceof

class Animal {
    greet() {
      // Do nothing.
    }
}

class Dog extends Animal {
  greet() {
    console.log("Woof!");
  }
}

class Cat extends Animal {
  greet() {
    console.log("Meow!");
  }
}

let dog = new Dog();

console.log(dog instanceof Animal); // Returns true
console.log(dog instanceof Dog); // Returns true
console.log(dog instanceof Cat); // Returns false
console.log(dog instanceof Object); // Caveat: returns true!

或者在ES5中:

function Animal() {
}

Animal.prototype.greet = function() {
  // Do nothing
}

function Dog() {
  Animal.call(this);
}

Dog.prototype = Object.create(Animal.prototype);

Dog.prototype.greet = function() {
  console.log("Woof!");
}

function Cat() {
  Animal.call(this);
}

Cat.prototype = Object.create(Animal.prototype);

Cat.prototype.greet = function() {
  console.log("Meow!");
}

var dog = new Dog();

console.log(dog instanceof Animal); // Returns true
console.log(dog instanceof Dog); // Returns true
console.log(dog instanceof Cat); // Returns false
console.log(dog instanceof Object); // Caveat: returns true!

注意:instanceof不是ES6功能,但类是。您可以将instanceof与ES5样式的原型一起使用。有关详细信息,请see MDN

相关问题