【问题标题】:How to implement validation with encapsulation如何通过封装实现验证
【发布时间】:2017-11-22 09:29:37
【问题描述】:

请先查看原始问题: Encapsulation in JavaScript with getter and setter

@Jacob 谢谢雅各布!这是很好的信息。我不太确定该解决方案如何工作,但将方法放入该返回子句效果很好。这是我的工作类定义:

function vehicle(thewheels, thecolour){
    var colour=thecolour;
    var wheels=thewheels > 4 ? '4' : thewheels;
    return {
            getcolour: function() {
            return colour; 
        },
            setcolour: function(value) { 
            colour = value;
        },
            getwheels: function() {
            return wheels; 
        },
            setwheels: function(value) { 
            wheels = value;
        }
    }
} 

我已经在构造函数中放入了一些代码(可能是更复杂的代码)来处理输入数据。我可以将相同的代码放入“setwheels”方法中,以便完全“保留”传入的数据;但是肯定有一种更简单的方法来管理输入数据而不必复制该代码?

我尝试将这个新函数放入类定义中:

setwheels: function(value) { 
    wheels = validwheels(value);
},
validwheels: function(wheelsin){
    return wheelsin > 4 ? 4 : wheelsin;
}

但是构造函数看不到'validwheels'函数。有没有办法在这个类中重用验证代码进行实例化和“设置”?

【问题讨论】:

  • 为什么不使用实际的属性访问器? get colour() { - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • @evolutionxbox 你的意思是,以下(如果我将私有属性重命名为 _colour 和 _wheels):get colour(){return _colour;} 如果是,那么我如何访问它?
  • 没有。不要重命名。没必要这样
  • 我在这里做了一个简短的例子来说明我的建议:jsbin.com/jaqiziliya/edit?js,console
  • 至于validwheels函数,不要放在返回对象中。你可以把它放在vehicle 函数体中。

标签: javascript interface get set encapsulation


【解决方案1】:

这是一个演示封装和验证的完整解决方案。感谢@Jacob 和@evolutionxbox 的大力协助!

     <button onclick="testOOP()">Click me</button>

     <script>
       //<!-- 
       function testOOP(){
        var v1 = new vehicle(40, "red"); //setting new values during instantiation
        var v2 = new vehicle(2, "blue");
        showVehDetails(v1);
        showVehDetails(v2);
        v2.wheels=10;           //validated input restricted to 4
        showVehDetails(v2);
        v2.colour="orange";     
        showVehDetails(v2);
        }

        function showVehDetails(v){
            document.write("This vehicle is " + v.colour + " and has " + v.wheels + " wheels.<br/>");
        }

        //*************'vehicle' - Class definition**************
function vehicle(thewheels, thecolour){
    var colour=thecolour;
    var wheels=validWheels(thewheels);
    function validWheels(wheelsin){
        return wheelsin > 4 ? 4 : wheelsin;
    }
    return {
            get colour() {
            return colour; 
        },
            set colour(value) { 
            colour = value;
        },
            get wheels() {
            return wheels; 
        },
            set wheels(value) { 
            wheels = validWheels(value);
        }
    }
} 
        //************End class definition************************
       //-->
     </script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2011-04-25
    • 2019-12-23
    相关资源
    最近更新 更多