2017-05-31 92 views
0

我一直在做一个关于干净的代码的课程。该课程规定,被“stringly”输入是一件坏事可读性,建议使用不同的结构(该课程采用C#):如何避免在Javascript中输入“字符串”?

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

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

我的问题是:我如何能实现像在JavaScript中的结构?

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

EmployeeType = { 
    Manager: "manager" 
} 

employee = { 
    Type: : "manager" 
} 

这是更好的方法吗?

+0

js是宽松打字,您应该使用'employeeType ===“manager”'而不是'employeeType ==“manager”'(REF:https://stackoverflow.com/questions/359494/哪些等于运营商与应该使用在JavaScript比较)为js宽松打字 –

+0

,看看这个:http://blog.jeremymartin.name/2008/03/understanding-loose -typing-in.html –

+2

不确定如何“宽松打字”是完全相关的! –

回答

0

如果您使用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

+1

ES5的等价物是不是涉及在'.prorotype'上创建'greet()'方法而不是直接在每个实例上创建?在任何情况下,这都不回答问题,该问题询问如何判断员工是否是经理,因为用OO表示的方式将是具有'type'属性的'Employee'实例,或者具有从'Employee'继承的'Manager'。 – nnnnnn

+0

@nnnnnn你是对的ES5原型;我已经更新了。没有看到涉及继承的需要(只想着说明OP如何使用'instanceof'而不是“stringly”类型),但已经更新了包含它的答案,因此它更类似于这个问题。 –

相关问题