使用hasOwnProperty()引用对象

时间:2016-08-13 05:21:30

标签: javascript jquery html css

我想在JavaScript中编写一个函数,将一个样式对象应用于html元素,但如果该对象存在则仅

示例,如果我有以下对象:

objMyObject {
    "idstring": {
        "style" : {
            "opacity": "0.50"
        }
    }
};

所以我使用 hasOwnProperty()在尝试应用之前先检查“style”是否存在 - 这样可以正常工作。

但是,让我们假设我的对象有多种样式:

objMyObject {
    "idstring1": {
        "style" : {
            "opacity": "0.50"
        }
    },

    "idstring2": {
        "style": {
            "opacity": "0.99"
        }
    },

    "idstring3": {
        "style": {
            "opacity": "0.50"
        }
    }

};

现在,有时这些单独的样式对象可以是相同的。上面的例子很简短,但是对象可以更大并且拥有多个样式属性,所以如果我可以执行以下操作会更好:

objMyObject {
    "idstring1": {
        "style" : {
            "opacity": "0.50"
        }
    },

    "idstring2": {
        "style": {
            "opacity": "0.99"
        }
    },

    "idstring3": {
        // This particular style object has the same properties as
        // idstring1
        "apply": "idstring1"
    }

};

所以我可以这样做:

if (objMyObject.hasOwnProperty("idstring3")) {
    if (objMyObject.idString3.hasOwnProperty("apply"))
        // Apply an existing, alternative style object.
        //
        $("#el").css(objMyObject.idstring3.apply)
    else if (objMyObject.idstring3.hasOwnProperty("style"))
        $("#el").css(objMyObject.idString3.style)
}

问题是第一次调用 hasOwnProperty()

if (objMyObject.hasOwnProperty("idstring3"))

评估为真,这很棒。但是,即使对象包含“样式”或“应用”对象,后续调用也会失败。

以下是我正在使用的完整代码:

// JavaScript object - the "mouseout" object should apply the
// "init" object.
//
var objHeader = {
    "targetID": "header",

    "init": {
        "style": {
            "backgroundColor": "#FF0000",
            "opacity": "0.00"
        }
    },

    "load": {
        "style": {
            "opacity": "0.50"
        }
    },

    "mouseover": {
        "style": {
            "opacity": "0.99"
        }
    },

    // Here, the elApply() function should apply the "style" defined
    // in "init".
    //
    "mouseout": {
        "apply": "init"
    }
};

这是我正在使用的两个功能:

// Apply a style to an object - will return false on error or true
// on success.
//
// State is the object to be applied, for example:
//
//    elApply(objHeader, "mouseout");
//
// To apply the style attached to "mouseout".
//
function elApply(
    objElement,
    objState
) {
    // Example - if elInit calls elApply(objHeader, "mouseout");
    // then will first look for objHeader.mouseout.apply, if that
    // exists then it should point to another object with a style
    // to be applied - if this is the case true is returned here
    // and all is well.
    //
    if (elApply(objElement.objState, "apply")) {
        alert("Applied 'apply' to " + objState);
        return true;
    }

    // No "apply" exists, so attempt to apply a "style"
    // object.
    //  
    if (objElement.objState.hasOwnProperty("style")) {
        $("#" + objElement.targetID).css(objElement.objState.style);
        return true;
    }

    alert("Neither '" + objState + "' nor 'apply' exist in this object!");
    return false;
}

function elInit(
    objElement
) {
    $(document).ready(function() {
        var targetID = objElement.targetID;         
        elApply(objElement, "mouseout");
    });
}

所以它的工作原理如下:

  1. elInit()函数调用 elApply(objElement,“mouseout”);
  2. “mouseout”属性存在, elApply()函数将 objElement.hasOwnProperty(“mouseout”)评估为
  3. 检查 objElement.mouseout.apply 是否存在,但显然 objElement.mouseout 未定义,尽管之前的 hasOwnProperty ()调用建议“mouseout”存在。
  4. 希望这是明确的,任何想法?这不是什么大问题,如果对象不重复,我可以重新使用已经定义的对象。

    也许我的逻辑/实现或对hasOwnProperty()的理解存在根本缺陷?如果是这样,有没有办法让父对象中的兄弟对象以这种方式相互引用?

    很有责任。

2 个答案:

答案 0 :(得分:2)

我建议事先填充对象中所有缺少的样式。然后,您的elStyle()功能变得更加简单,因为它不再需要关注apply属性。

从技术上讲,将样式从一个元素复制到另一个元素只是对对象的引用的副本。所以,这是一个廉价的操作。

此代码中do{} while()循环的原因是支持应用链#' (比如我的例子中的mouseout0 > mouseout > init)。如果从未遇到过这种情况,您可以安全地删除它。



var objHeader = {
    "targetID": "header",

    "init": {
        "style": { "backgroundColor": "#FF0000", "opacity": "0.75" }
    },
    "load": {
        "style": { "opacity": "0.50" }
    },
    "mouseover": {
        "style": { "opacity": "0.99" }
    },
    "mouseout0": {
        "apply": "mouseout"
    },
    "mouseout": {
        "apply": "init"
    }
};

function populateStyle(o) {
  var success;
  
  do {
    success = false;

    Object.keys(o).filter(
      function(k) {
        return o[k].hasOwnProperty('apply');
      }
    ).forEach(
      function(k) {
        if(o.hasOwnProperty(o[k].apply) && o[o[k].apply].hasOwnProperty('style')) {
          o[k].style = o[o[k].apply].style;
          delete o[k].apply;
          success = true;
        }
      }
    );
  } while(success);
}

function elStyle(objElement, state) {
  if(objElement.hasOwnProperty(state) && objElement[state].hasOwnProperty('style')) {
    $('#' + objElement.targetID).css(objElement[state].style);
  }
  else {
    // error: style undefined
  }
}

populateStyle(objHeader);
elStyle(objHeader, 'mouseout0');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">Hello World</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

请删除大写'S'并在下面的代码中填写小号。

(objMyObject.idString3.hasOwnProperty( “应用”)) 替换为

(objMyObject.idstring3.hasOwnProperty( “应用”))

因为JavaScript区分大小写。

我认为这会有所帮助。