hasAttribute vs hasOwnProperty

NDa*_*vis 7 html javascript jquery attributes

我遇到了一些jquery代码,它试图使用hasOwnProperty来访问html属性.

<input type="text" name="fname" placeholder="First name">

<script>
    var e = $element.find('input')[0];
    if(!e.hasOwnProperty("placeholder")){...}
</script>
Run Code Online (Sandbox Code Playgroud)

据我所知,这应该永远是

if(!e.hasAttribute("placeholder")){...}
Run Code Online (Sandbox Code Playgroud)

但是hasAttribute和hasOwnProperty有什么区别?它们是否相同?

Ian*_*mos 11

hasAttribute()

hasAttribute() 仅适用于html元素,如果该元素与给定参数具有相同的属性名称,则返回true.

<div class="myClass"></div>

<script>
    document.querySelector('div').hasAttribute('class'); //true
    document.querySelector('div').hasOwnProperty('class'); //false
</script>
Run Code Online (Sandbox Code Playgroud)

hasOwnProperty()

hasOwnProperty() 仅适用于JavaScript对象,如果该对象具有与给定参数同名的属性,则返回true.

var obj = {
    myProp: "my attribute"
}

obj.hasOwnProperty("myProp") //true
obj.hasAttribute("myProp") //false
Run Code Online (Sandbox Code Playgroud)

一些html元素可以在javascript中构建,这就是为什么hasOwnProperty有时会为它工作,但hasAttribute永远不适用于javascript对象.