Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

object - JavaScript - Identify whether a property is defined and set to 'undefined', or undefined

Say I have the following code:

function One() {}
One.prototype.x = undefined;

function Two() {}

var o = new One();
var t = new Two();

o.x and t.x will both evaluate to undefined. o.hasOwnProperty('x') and t.hasOwnProperty('x') will both return false; the same goes for propertyIsEnumerable. Two questions:

  • Is there any way to tell that o.x is defined and set to undefined?
  • Is there ever any reason to? (should the two be semantically equivalent?)

A small caveat: doing (for propName in o) loop will yield 'x' as one of the strings, while doing it in t will not - so there IS a difference in how they're represented internally (at least in Chrome).

question from:https://stackoverflow.com/questions/385960/javascript-identify-whether-a-property-is-defined-and-set-to-undefined-or-u

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A slightly simpler way than your method is to use the Javascript in operator

alert('x' in o); // true
alert('x' in t); // false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...