请先看原帖: Encapsulation in JavaScript with getter and setter
@Jacob谢谢雅各布!这是很好的信息。我不太确定该解决方案是如何工作的,但将方法放入该return子句中效果很好。这是我的工作类定义:
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'方法中,以便完全“保持”进入的数据;但是,必须有一种更简单的方法来管理输入数据而不必复制该代码吗?
我尝试将这个新函数放入Class定义中:
setwheels: function(value) {
wheels = validwheels(value);
},
validwheels: function(wheelsin){
return wheelsin > 4 ? 4 : wheelsin;
}
但构造函数无法看到'validwheels'函数。有没有办法在这个类中重新使用验证代码进行实例化和“设置”?
答案 0 :(得分: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>