我需要为对象编写自己的set函数。但这不会更改属性的值。我在另一个js文件中调用该函数。
function parameterSet(ifFloat, variable, newValue, max){
if(newValue >= 0 && newValue <= max){
if(ifFloat)
variable = newValue;
else
variable = Math.floor(newValue);
}
}
exports.lightObject.prototype.changeLightStartTime = function(newValue){
parameterSet(true, this.lightStartTime, newValue, 23);
};
exports.lightObject.prototype.changeLightDurationTime = function(newValue){
parameterSet(true, this.lightDurationTime, newValue, 23);
};
socket.on('newLightParam', function(data){
light.lightStartTime = data.newLightStart; // this one works
light.changeLightDurationTime(data.newLightLength); // this one doesn't
});
发生这种情况的原因是,这样做会丢失对该对象的引用。您可以将对象传递给该函数,并在该函数内部更改lightDurationTime属性。
function parameterSet(ifFloat, variable, newValue, max){
if(newValue >= 0 && newValue <= max){
if(ifFloat)
variable.lightStartTime = newValue;
else
variable.lightStartTime = Math.floor(newValue);
}
}
exports.lightObject.prototype.changeLightStartTime = function(newValue){
parameterSet(true, this, newValue, 23);
};
或者,如果您想使其更通用:
function parameterSet(ifFloat, variable, attribute, newValue, max){
if(newValue >= 0 && newValue <= max){
if(ifFloat)
variable[attribute] = newValue;
else
variable[attribute] = Math.floor(newValue);
}
}
exports.lightObject.prototype.changeLightStartTime = function(newValue){
parameterSet(true, this, 'lightStartTime', newValue, 23);
};
socket.on('newLightParam', function(data){
light.lightStartTime = data.newLightStart; // this one works
light.changeLightDurationTime(data.newLightLength); // this one doesn't
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句