JavaScript 中 Property 和 Attribute 的區別詳解

最近看企鵝羣 ,發現li的value有個‘好玩’的默認“規則”,搜索一番發現是Property 與Attribute 的緣故,無奈最初不清楚,最後搜到如下一篇文章,算是瞭解了點。現偷偷運輸過來,供大家欣賞(最後附有原文以及其他”可能”有幫助的)。

property 和 attribute非常容易混淆,兩個單詞的中文翻譯也都非常相近(property:屬性,attribute:特性),但實際上,二者是不同的東西,屬於不同的範疇。

  • property是DOM中的屬性,是JavaScript裏的對象;
  • attribute是HTML標籤上的特性,它的值只能夠是字符串;

基於JavaScript分析property 和 attribute

html中有這樣一段代碼:

<input id="in_1" value="1" sth="whatever">

簡單的在html頁面上創建一個input輸入欄(注意在這個標籤中添加了一個DOM中不存在的屬性“sth”),此時在JS執行如下語句

var in1 = document.getElementById('in_1');

執行語句

console.log(in1);

從console的打印結果,可以看到in1含有一個名爲“attributes”的屬性,它的類型是NamedNodeMap,同時還有“id”和“value”兩個基本的屬性,但沒有“sth”這個自定義的屬性。

attributes: NamedNodeMap
value: "1"
id: "in_1"

有些console可能不會打印in1上的屬性,那麼可以執行以下命令打印要觀察的屬性:

console.log(in1.id);		// 'in_1'
console.log(in1.value);		// 1
console.log(in1.sth);		// undefined

可以發現,標籤中的三個屬性,只有“id”和“value”會在in1上創建,而“sth”不會被創建。這是由於,每一個DOM對象都會有它默認的基本屬性,而在創建的時候,它只會創建這些基本屬性,我們在TAG標籤中自定義的屬性是不會直接放到DOM中的。

我們做一個額外的測試,創建另一個input標籤,並執行類似的操作:

html:

<input id="in_2">

JS:

var in2 = document.getElementById('in_2');
console.log(in2);

從打印信息中可以看到:

id: "in_2"
value: null

儘管我們沒有在TAG中定義“value”,但由於它是DOM默認的基本屬性,在DOM初始化的時候它照樣會被創建。由此我們可以得出結論:

  • DOM有其默認的基本屬性,而這些屬性就是所謂的“property”,無論如何,它們都會在初始化的時候再DOM對象上創建。
  • 如果在TAG對這些屬性進行賦值,那麼這些值就會作爲初始值賦給DOM的同名property。

現在回到第一個input(“#in_1”),我們就會問,“sth”去哪裏了?別急,我們把attributes這個屬性打印出來看看

console.log(in2);

上面有幾個屬性:

0: id
1: value
2: sth
length: 3
__proto__: NamedNodeMap

原來“sth”被放到了attributes這個對象裏面,這個對象按順序記錄了我們在TAG中定義的屬性和屬性的數量。此時,如果再將第二個input標籤的attributes打印出來,就會發現只有一個“id”屬性,“length”爲1。

從這裏就可以看出,attributes是屬於property的一個子集,它保存了HTML標籤上定義屬性。如果再進一步探索attitudes中的每一個屬性,會發現它們並不是簡單的對象,它是一個Attr類型的對象,擁有NodeType、NodeName等屬性。關於這一點,稍後再研究。注意,打印attribute屬性不會直接得到對象的值,而是獲取一個包含屬性名和值的字符串,如:

console.log(in1.attibutes.sth);		// 'sth="whatever"'

由此可以得出:

  • HTML標籤中定義的屬性和值會保存該DOM對象的attributes屬性裏面;
  • 這些attribute屬性的JavaScript中的類型是Attr,而不僅僅是保存屬性名和值這麼簡單;

那麼,如果我們更改property和attribute的值會出現什麼效果呢?執行如下語句:

in1.value = 'new value of prop';
console.log(in1.value);				// 'new value of prop'
console.log(in1.attributes.value);

此時,頁面中的輸入欄的值變成了“new value of prop”,而propety中的value也變成了新的值,但attributes卻仍然是“1”。從這裏可以推斷,property和attribute的同名屬性的值並不是雙向綁定的。

如果反過來,設置attitudes中的值,效果會怎樣呢?

in1.attributes.value.value = 'new value of attr';
console.log(in1.value);				// 'new value of attr'
console.log(in1.attributes.value);	// 'new value of attr'

此時,頁面中的輸入欄得到更新,property中的value也發生了變化。此外,執行下面語句也會得到一樣的結果

in1.attributes.value.nodeValue = 'new value of attr';

由此,可得出結論:

  • property能夠從attribute中得到同步
  • attribute不會同步property上的值
  • attribute和property之間的數據綁定是單向的,attribute->property;
  • 更改property和attribute上的任意值,都會將更新反映到HTML頁面中;

基於jQuery分析attribute和property

那麼jQuery中的attr和prop方法是怎樣的呢?

首先利用jQuery.prop來測試

$(in1).prop('value', 'new prop form $');

console.log(in1.value);				// 'new prop form $'
console.log(in1.attributes.value);	// '1'

輸入欄的值更新了,但attribute並未更新。

然後用jQuery.attr來測試

$(in1).attr('value', 'new attr form $');

console.log(in1.value);				// 'new attr form $'
console.log(in1.attributes.value);	// 'new attr form $'

輸入欄的值更新了,同時property和attribute都更新了。

從上述測試的現象可以推斷,jQuery.attr和jQuery.prop基本和原生的操作方法效果一致,property會從attribute中獲取同步,然而attribute不會從property中獲取同步。那麼jQuery到底是如何實現的呢?

下面,我們來看看jQuery.attr和jQuery.prop的源碼。

jQuery源碼

$().prop源碼

jQuery.fn.extend({
	prop: function( name, value ) {
		return access( this, jQuery.prop, name, value, arguments.length > 1 );
	},
	... // removeProp方法
});

$().attr源碼

jQuery.fn.extend({
	attr: function( name, value ) {
		return access( this, jQuery.attr, name, value, arguments.length > 1 );
	},
	... // removeAttr方法
});

無論是attr還是prop,都會調用access方法來對DOM對象的元素進行訪問,因此要研究出更多內容,就必須去閱讀access的實現源碼。

jQuery.access

// 這是一個多功能的函數,能夠用來獲取或設置一個集合的值
// 如果這個“值”是一個函數,那麼這個函數會被執行

// @param elems, 元素集合
// @param fn, 對元素進行處理的方法
// @param key, 元素名
// @param value, 新的值
// @param chainable, 是否進行鏈式調用
// @param emptyGet,
// @param raw, 元素是否一個非function對象
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
	var i = 0,						// 迭代計數
		length = elems.length,		// 元素長度
		bulk = key == null;			// 判斷是否有特定的鍵(屬性名)

	// 如果存在多個屬性,遞歸調用來逐個訪問這些值
	if ( jQuery.type( key ) === "object" ) {
		chainable = true;
		for ( i in key ) {
			jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
		}

	// 設置一個值
	} else if ( value !== undefined ) {
		chainable = true;

		if ( !jQuery.isFunction( value ) ) {	// 如果值不是一個function
			raw = true;
		}

		if ( bulk ) {
			// Bulk operations run against the entire set
			// 如果屬性名爲空且屬性名不是一個function,則利用外部處理方法fn和value來執行操作
			if ( raw ) {
				fn.call( elems, value );
				fn = null;

			// ...except when executing function values
			// 如果value是一個function,那麼就重新構造處理方法fn
			// 這個新的fn會將value function作爲回調函數傳遞給到老的處理方法
			} else {
				bulk = fn;
				fn = function( elem, key, value ) {
					return bulk.call( jQuery( elem ), value );
				};
			}
		}

		if ( fn ) {	// 利用處理方法fn對元素集合中每個元素進行處理
			for ( ; i < length; i++ ) {
				fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
				// 如果value是一個funciton,那麼首先利用這個函數返回一個值並傳入fn
			}
		}
	}

	return chainable ?
		elems :			// 如果是鏈式調用,就返回元素集合

		// Gets
		bulk ?
			fn.call( elems ) :
			length ? fn( elems[0], key ) : emptyGet;
};

access方法雖然不長,但是非常繞,要完全讀懂並不簡單,因此可以針對jQuery.fn.attr的調用來簡化access。

jQuery.fn.attr/ jQuery.fn.prop 中的access調用

$().attr的調用方式:

  • $().attr( propertyName ) // 獲取單個屬性
  • $().attr( propertyName, value ) // 設置單個屬性
  • $().attr( properties ) // 設置多個屬性
  • $().attr( propertyName, function ) // 對屬性調用回調函數

prop的調用方式與attr是一樣的,在此就不重複列舉。爲了簡單起見,在這裏只對第一和第二種調用方式進行研究。

調用語句:

access( this, jQuery.attr, name, value, arguments.length > 1 );

簡化的access:

// elems 當前的jQuery對象,可能包含多個DOM對象
// fn jQuery.attr方法
// name 屬性名
// value 屬性的值
// chainable 如果value爲空,則chainable爲false,否則chainable爲true

var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {

	var i = 0,						// 迭代計數
		length = elems.length,		// 屬性數量
		bulk = false;				// key != null

	if ( value !== undefined ) {	// 如果value不爲空,則爲設置新值,否則返回該屬性的值
		chainable = true;
		raw = true;				// value不是function

		if ( fn ) {	// fn爲jQuery.attr
			for ( ; i < length; i++ ) {
				fn( elems[i], key, value);		// jQuery.attr(elems, key, value);
			}
		}
	}

	if(chainable) {			// value不爲空,表示是get
		return elems;		// 返回元素實現鏈式調用
	} else {
		if(length) {		// 如果元素集合長度不爲零,則返回第一個元素的屬性值
			return fn(elems[0], key); 	// jQuery.attr(elems[0], key);
		} else {
			return emptyGet;		// 返回一個默認值,在這裏是undefined
		}
	}
};

通過簡化代碼,可以知道,access的作用就是遍歷上一個$調用得到的元素集合,對其調用fn函數。在jQuery.attr和jQuery.prop裏面,就是利用access來遍歷元素集合並對其實現對attribute和property的控制。access的源碼裏面有多段條件轉移代碼,看起來眼花繚亂,其最終目的就是能夠實現對元素集合的變量並完成不同的操作,複雜的代碼讓jQuery的接口變得更加簡單,能極大提高代碼重用性,意味着減少了代碼量,提高代碼的密度從而使JS文件大小得到減少。

這些都是題外話了,現在回到$().attr和$().prop的實現。總的說,這兩個原型方法都利用access對元素集進行變量,並對每個元素調用jQuery.prop和jQuery.attr方法。要注意,這裏的jQuery.prop和jQuery.attr並不是原型鏈上的方法,而是jQuery這個對象本身的方法,它是使用jQuery.extend進行方法擴展的(jQuery.fn.prop和jQuery.fn.attr是使用jQuery.fn.extend進行方法擴展的)。

下面看看這兩個方法的源碼。

jQury.attr

jQuery.extend({
	attr: function( elem, name, value ) {
		var hooks, ret,
			nType = elem.nodeType;	// 獲取Node類型

		// 如果 elem是空或者NodeType是以下類型
		// 		2: Attr, 屬性, 子節點有Text, EntityReference
		// 		3: Text, 元素或屬性中的文本內容
		// 		8: Comment, 註釋
		// 不執行任何操作
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// 如果支持attitude方法, 則調用property方法
		if ( typeof elem.getAttribute === strundefined ) {
			return jQuery.prop( elem, name, value );
		}

		// 如果elem的Node類型不是元素(1)
		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
			name = name.toLowerCase();
			// 針對瀏覽器的兼容性,獲取鉤子函數,處理一些特殊的元素
			hooks = jQuery.attrHooks[ name ] ||
				( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
		}

		if ( value !== undefined ) {		// 如果value不爲undefined,執行"SET"

			if ( value === null ) {			// 如果value爲null,則移除attribute
				jQuery.removeAttr( elem, name );

			} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;					// 使用鉤子函數

			} else {						// 使用Dom的setAttribute方法
				elem.setAttribute( name, value + "" );		// 注意,要將value轉換爲string,因爲所有attribute的值都是string
				return value;
			}

		// 如果value爲undefined,就執行"GET"
		} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
			return ret;			// 使用鉤子函數

		} else {
			ret = jQuery.find.attr( elem, name );	// 實際上調用了Sizzle.attr,這個方法中針對兼容性問題作出處理來獲取attribute的值

			// 返回獲得的值
			return ret == null ?
				undefined :
				ret;
		}
	},

	...
});

從代碼可以發現,jQuery.attr調用的是getAttribute和setAttribute方法。

jQeury.prop

jQuery.extend({

	...
	prop: function( elem, name, value ) {
		var ret, hooks, notxml,
			nType = elem.nodeType;

		// 過濾註釋、Attr、元素文本內容
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );

		if ( notxml ) {		// 如果不是元素
			name = jQuery.propFix[ name ] || name;	// 修正屬性名
			hooks = jQuery.propHooks[ name ];		// 獲取鉤子函數
		}

		if ( value !== undefined ) {		// 執行"SET"
			return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
				ret :						// 調用鉤子函數
				( elem[ name ] = value );	// 直接對elem[name]賦值

		} else {							// 執行"GET"
			return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
				ret :				// 調用鉤子函數
				elem[ name ];		// 直接返回elem[name]
		}
	},

	...
});

jQuery.prop則是直接對DOM對象上的property進行操作。

通過對比jQuery.prop和jQuery.attr可以發現,前者直接對DOM對象的property進行操作,而後者會調用setAttribute和getAttribute方法。setAttribute和getAttribute方法又是什麼方法呢?有什麼效果?

setAttribute和getAttribute

基於之前測試使用的輸入框,執行如下代碼:

in1.setAttribute('value', 'new attr from setAttribute');

console.log(in1.getAttribute('value'));			// 'new attr from setAttribute'
console.log(in1.value);							// 'new attr from setAttribute'
console.log(in1.attributes.value);				// 'value="new attr from setAttribute"',實際是一個Attr對象

執行完setAttribute以後,就如同直接更改attributes中的同名屬性; 而getAttribute的結果與訪問property的結果一模一樣,而不會像直接訪問attritudes那樣返回一個Attr對象。

特殊的例子

href

然而,是不是所有標籤,所有屬性都維持保持這樣的特性呢?下面我們看看href這個屬性/特性。

首先在html中創建一個標籤:

<a href='page_1.html' id='a_1'></a>

在JS腳本中執行如下代碼:

console.log(a1.href);	// 'file:///D:/GitHub/JS/html/test_01/page_1.html'
console.log(a1.getAttribute('href'));	// 'page_1.html'

可以看到,property中保存的是絕對路徑,而attribute中保存的是相對路徑。那麼,如果更改了這些值會發生什麼情況呢?

更改attribute:

a1.setAttribute('href', 'page_2.html');		// 相對路徑
console.log(a1.href);	// 'file:///D:/GitHub/JS/html/test_01/page_2.html'
console.log(a1.getAttribute('href'));	// 'page_2.html'

a1.setAttribute('href', '/page_3.html');	// 根目錄路徑
console.log(a1.href);						// 'file:///D:/page_3.html'
console.log(a1.getAttribute('href'));		// '/page_3.html'

更改property:

a1.href = 'home.html';	// 相對路徑
console.log(a1.href);	// 'file:///D:/GitHub/JS/html/test_01/home.html'
console.log(a1.getAttribute('href'));	// 'home.html'

a1.href = '/home.html';	// 根目錄路徑
console.log(a1.href);	// 'file:///D:/home.html'
console.log(a1.getAttribute('href'));	// '/home.html'

從這裏可以發現,href是特殊的屬性/特性,二者是雙向綁定的,更改任意一方,都會導致另一方的的值發生改變。而且,這並不是簡單的雙向綁定,property中的href永遠保存絕對路徑,而attribute中的href則是保存相對路徑。

看到這裏,attribute和property的區別又多了一點,然而,這又讓人變得更加疑惑了。是否還有其他類似的特殊例子呢?

id

嘗試改變property中的id:

	a1.id = 'new_id';
	console.log(a1.id);						// 'new_id'
	console.log(a1.getAttribute('id'));		// 'new_id'

天呀,現在attribute中的id從property中的id發生了同步,數據方向變成了property <=> attribute

disabled

再來看看disabled這個屬性,我們往第一個添加“disabled”特性:

<input id="in_1" value="1" sth="whatever" disabled='disabled'>	// 此時input已經被禁用了

然後執行下面的代碼:

console.log(in1.disabled);		// true
in1.setAttribute('disabled', false);	// 設置attribute中的disabled,無論是false還是null都不會取消禁用
console.log(in1);				// true
console.log(in1.getAttribute('disabled'));	// 'false'

改變attributes中的disabled不會改變更改property,也不會取消輸入欄的禁用效果。

如果改成下面的代碼:

console.log(in1.disabled);		// true
in1.disabled = false;			// 取消禁用
console.log(in1.disabled);		// false
console.log(in1.getAttribute('disabled'));	// null,attribute中的disabled已經被移除了

又或者:

console.log(in1.disabled);		// true
in1.removeAttribute('disabled');	// 移除attribute上的disabled來取消禁用
console.log(in1.disabled);		// false
console.log(in1.getAttribute('disabled'));	// null,attribute中的disabled已經被移除了

可以發現,將property中的disabled設置爲false,會移除attributes中的disabled。這樣數據綁定又變成了,property<=>attribute;

所以property和attritude之間的數據綁定問題並不能單純地以“property<-attribute”來說明。

總結

分析了這麼多,對property和attribute的區別理解也更深了,在這裏總結一下:

創建

  • DOM對象初始化時會在創建默認的基本property;
  • 只有在HTML標籤中定義的attribute纔會被保存在property的attributes屬性中;
  • attribute會初始化property中的同名屬性,但自定義的attribute不會出現在property中;
  • attribute的值都是字符串

數據綁定

  • attributes的數據會同步到property上,然而property的更改不會改變attribute;
  • 對於value,class這樣的屬性/特性,數據綁定的方向是單向的,attribute->property
  • 對於id而言,數據綁定是雙向的,attribute<=>property
  • 對於disabled而言,property上的disabled爲false時,attribute上的disabled必定會並存在,此時數據綁定可以認爲是雙向的;

使用

  • 可以使用DOM的setAttribute方法來同時更改attribute;
  • 直接訪問attributes上的值會得到一個Attr對象,而通過getAttribute方法訪問則會直接得到attribute的值;
  • 大多數情況(除非有瀏覽器兼容性問題),jQuery.attr是通過setAttribute實現,而jQuery.prop則會直接訪問DOM對象的property;

到這裏爲止,得出,property是DOM對象自身就擁有的屬性,而attribute是我們通過設置HTML標籤而給之賦予的特性,attribute和property的同名屬性/特性之間會產生一些特殊的數據聯繫,而這些聯繫會針對不同的屬性/特性有不同的區別。

事實上,在這裏,property和attribute之間的區別和聯繫難以用簡單的技術特性來描述,我在StackFlow上找到如下的回答,或者會更加接近於真正的答案:

These words existed way before Computer Science came around. Attribute is a quality or object that we attribute to someone or something. For example, the scepter is an attribute of power and statehood.

Property is a quality that exists without any attribution. For example, clay has adhesive qualities; or, one of the properties of metals is electrical conductivity. Properties demonstrate themselves though physical phenomena without the need attribute them to someone or something. By the same token, saying that someone has masculine attributes is self-evident. In effect, you could say that a property is owned by someone or something.

To be fair though, in Computer Science these two words, at least for the most part, can be used interchangeably – but then again programmers usually don’t hold degrees in English Literature and do not write or care much about grammar books .

最關鍵的兩句話:

  • attribute(特性),是我們賦予某個事物的特質或對象。
  • property(屬性),是早已存在的不需要外界賦予的特質。

參考資料

原文地址

JavaScript 中 Property 和 Attribute 的區別詳解

其他

html標籤屬性(attribute)和dom元素的屬性(property)  (只是由於感覺佈局有點亂,所以沒細看)

"attribute" 和 "property" 的區別是什麼 (百度知道的,說了下兩者的聯繫與區別,由於佈局,你懂得,同上)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章