JS中Attribute 和prototype 的区别是什么

JavaScript032

JS中Attribute 和prototype 的区别是什么,第1张

1、Attribute:是获取属性的值$("obj").attribute("id"),或设置属性$("obj").attribute("id",1)是一个方法。

2、prototype:prototype 属性使您有能力向对象添加属性和方法。 语法 object.prototype.name=value实例

JS中attr和prop属性的区别如下:

1、attr是attribute的缩写,是一个特性节点,每个DOM元素都有一个对应的attributes属性来存放所有的attribute节点,attributes是一个类数组的容器,说得准确点就是NameNodeMap,总之就是一个类似数组但又和数组不太一样的容器。attributes的每个数字索引以名值对(name=”value”)的形式存放了一个attribute节点。

<div class="box" id="box" gameid="880">hello</div>

上面的div元素的HTML代码中有class、id还有自定义的gameid,这些特性都存放在attributes中,类似下面的形式:

[ class="box", id="box", gameid="880" ]

可以这样来访问attribute节点:

var elem = document.getElementById( 'box' )

console.log( elem.attributes[0].name )// class

console.log( elem.attributes[0].value )// box

2、与之对应的property属性,比较特殊的是一些值为Boolean类型的property,如一些表单元素:

<input type="radio" checked="checked" id="raido">

var radio = document.getElementById( 'radio' )

console.log( radio.getAttribute('checked') )// checked

console.log( radio.checked )// true

对于这些特殊的attribute节点,只有存在该节点,对应的property的值就为true,如:

<input type="radio" checked="anything" id="raido">

var radio = document.getElementById( 'radio' )

console.log( radio.getAttribute('checked') )// anything

console.log( radio.checked )// true

3、了更好的区分attribute和property,基本可以总结为attribute节点都是在HTML代码中可见的,而property只是一个普通的名值对属性。