函数不会更改对象属性的值

时间:2019-02-15 22:36:41

标签: javascript

我需要为对象编写自己的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    
});

2 个答案:

答案 0 :(得分:0)

之所以会这样,是因为这样做会丢失对该对象的引用。 您可以将对象传递给该函数,然后在该函数内更改 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    
});

答案 1 :(得分:0)

首先,请注意下一行:

  

parameterSet(true,this.lightDurationTime,newValue,23);

this.lightDurationTime将是一个原始值,并按值传递给parameterSet()方法。因此,您将丢失对this的引用。您可能没有想到,您没有将内存引用传递给value。但是,一个简单的解决方法是将引用传递给this和要更改的属性:

  

parameterSet(true,this,“ lightDurationTime”,newValue,23);

示例:

function parameterSet(ifFloat, obj, property, newValue, max)
{
    if (newValue >= 0 && newValue <= max)
    {
        if (ifFloat)
            obj[property] = newValue;
         else
            obj[property] = Math.floor(newValue);
    }
}

var lightObject = function()
{
    this.lightStartTime = 0,
    this.lightDurationTime = 0
};

lightObject.prototype.changeLightStartTime = function(newValue)
{
    parameterSet(true, this, "lightStartTime", newValue, 23);
};

lightObject.prototype.changeLightDurationTime = function(newValue)
{
    parameterSet(true, this, "lightDurationTime", newValue, 23);
};

let light = new lightObject();
light.lightStartTime = 5;
console.log(light.lightStartTime);
light.changeLightDurationTime(10);
console.log(light.lightDurationTime);

相关问题