2015-09-09 24 views
0

对于5个“同类”原型函数,我得到了CodeClimate的重复副本,作为导致D评级的重复。如何在JavaScript中结合原型函数样式?

我的知识缺乏如何组合/不重复类似的代码来改善我的“代码风格”。对你的帮助表示感谢。

的原型:

SomeThing.prototype.destination = function(path) { 
    if (!arguments.length) { 
    return this.path(this._destination); 
    } 
    assert(is.string(path), 'You must pass a destination path string.'); 

SomeThing.prototype.frontmatter = function(frontmatter) { 
    if (!arguments.length) { 
    return this._frontmatter; 
    } 
    assert(is.boolean(frontmatter), 'You must pass a boolean.'); 

SomeThing.prototype.clean = function(clean) { 
    if (!arguments.length) { 
    return this._clean; 
    } 
    assert(is.boolean(clean), 'You must pass a boolean.'); 

SomeThing.prototype.concurrency = function(max) { 
    if (!arguments.length) { 
    return this._concurrency; 
    } 
    assert(is.number(max), 'You must pass a number for concurrency.'); 
+0

你是什么意思与 “合”?你想避免重复'SomeThing.prototype'?然后使用Object.assign。 – Oriol

+0

我认为重复是arguments.length检查加上相似的断言。 –

+0

我确实相信你们俩都是对的 - @ Travis。我一直在看这[Mozilla文档](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign),但正如我所说,我的知识并没有帮助我有了这个。 – CelticParser

回答

0

这会干出你的代码:

function makeProp(prop, type) { 
    return function(someArg) { 
     if (!arguments.length) return this['_' + prop]; 
     var msg = 'You must pass a ' + type + ' for ' + prop; 
     assert(is[type], msg) 
    } 
} 

Something.prototype = { 
    destination: makeProp('destination', 'string'), 
    frontmatter: makeProp('frontmatter', 'boolean'), 
    clean: makeProp('clean', 'boolean'), 
    concurrency: makeProp('concurrency', 'number') 
} 
+0

这正是我现在正在做的。 – CelticParser

+0

如果你需要进一步干掉你的代码,你可以换掉'makeProp'中的参数顺序,然后做'var makeBoolean = makeProp.bind(makeProp,'boolean')'然后'Something.prototype。 frontmatter = makeBoolean('frontmatter');',如果你有其他使用这些方法的方法,'string'和'number'是相同的。 – caasjj