2017-05-31 22 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」類型),但已經更新了包含它的答案,因此它更類似於這個問題。 –

相關問題