如何避免被“拒绝”;严格地;输入Javascript?

如何避免被“拒绝”;严格地;输入Javascript?,javascript,refactoring,Javascript,Refactoring,我一直在学习一门关于干净代码的课程。本课程指出,“严格”类型对可读性是一件坏事,并建议使用不同的结构(本课程使用C#): 我的问题是:如何在javascript中实现这样的结构 我应该创建一个像这样的对象吗 EmployeeType = { Manager: "manager" } employee = { Type: : "manager" } 这是更好的方法吗?如果使用ES6和类,可以使用instanceof class Animal { greet() {

我一直在学习一门关于干净代码的课程。本课程指出,“严格”类型对可读性是一件坏事,并建议使用不同的结构(本课程使用C#):

我的问题是:如何在javascript中实现这样的结构

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

EmployeeType = {
    Manager: "manager"
}

employee = {
    Type: : "manager"
}

这是更好的方法吗?

如果使用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样式的原型。要了解更多信息,

js是松散类型,您应该使用
employeeType==“manager”
而不是
employeeType==“manager”
(参考:)对于js松散类型,请看一看:不确定“松散类型”有多大关系!ES5是否会涉及在
.prorotype
上创建
greet()
方法,而不是直接在每个实例上创建?在任何情况下,这都不能回答这样一个问题,即如何判断员工是否是经理,因为表示这一点的OO方式是使用
类型
属性的
employee
实例,或者拥有继承自
employee
@nnnnnn您在ES5原型上是对的
经理
;我已经更新了。没有看到涉及继承的必要性(只是想展示OP如何使用
instanceof
而不是“stringly”类型),但已经更新了答案,将其包括在内,因此它更类似于这个问题。
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!