JavaScript中四種不同的屬性檢測方式比較

來源:互聯網
上載者:User

標籤:span   表示   false   區分   ble   方法   繼承   asc   log   

JavaScript中四種不同的屬性檢測方式比較1. 用in方法
var o = {x:1};"x" in o; //true"y" in o; //false"toString" in o; //true,繼承屬性可以被檢測到"toString" in Object.prototype; //true,不可枚舉的屬性可以被檢測到

 

 2. hasOwnProperty()方法

var o = {x:1};o.hasOwnProperty("x"); //trueo.hasOwnProperty("y"); //falseo.hasOwnProperty("toString"); //false,無法檢測繼承屬性Object.prototype.hasOwnProperty("toString"); //true,不可枚舉的屬性可以被檢測到
3. propertyIsEnumerable()方法
var o = Object.create({y:2});o.x = 1;o.propertyIsEnumerable("x"); //true,x是可枚舉的屬性o.propertyIsEnumerable("y"); //false,繼承屬性,不可枚舉Object.prototype.propertyIsEnumerable("toString"); //false,不可枚舉的屬性無法被檢測

 

4. !== undefined方法
var o = {x : 1};o.x !== undefined; //true,o中有屬性xo.toString !== undefined; //true,繼承屬性也可以被檢測到

這種方法的一個弱點是,無法區分不存在的屬性和存在但值為undefined的值,如:

var o = {x : undefined};o.x !== undefined; //false"x" in o; //true

注意這裡用的是"!=="而不是"!=",因為"!=="可以區分undefined和null。 
但有時候不用區分"null"和"undefined",只要判斷一個屬性不是null或undefined即可。

//如果o含有屬性x,且x的值不是undefined或null,o.x乘以2if(o.x != null) o.x *= 2;

繼承屬性是不可枚舉的,所以能檢測繼承屬性的,肯定也能檢測到不可枚舉屬性。 
×表示無法檢測,√表示可以檢測

檢測方法 不可枚舉屬性? 繼承屬性?
in
hasOwnProperty ×
propertyIsEnumerable × ×
!==

JavaScript中四種不同的屬性檢測方式比較

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.