JavaScript: Is a member defined?

徘徊边缘 提交于 2019-12-04 15:48:41

问题


It seems to me that there are four different ways I can determine whether a given object (e.g. foo) has a given property (e.g. bar) defined:

  1. if (foo.hasOwnProperty(bar)) {
  2. if ('bar' in foo) {
  3. if (typeof foo.bar !== 'undefined') {
  4. if (foo.bar === undefined) {

To determine if there is a property named "bar" in the object foo, are all three of those statements equivalent? Are there any sublte semantics I don't know that makes any of these three statements different?


回答1:


No they are totally different. Example:

foo = {bar: undefined};
Object.prototype.baz = undefined;
Object.prototype.bing = "hello";

Then:

(typeof foo.bar != "undefined")  === false
('bar' in foo)                   === true
(foo.hasOwnProperty('bar'))      === true


(typeof foo.baz != "undefined")  === false
('baz' in foo)                   === true
(foo.hasOwnProperty('baz'))      === false


(typeof foo.bing != "undefined") === true
('bing' in foo)                  === true
(foo.hasOwnProperty('bing'))     === false

Logic-wise:

  • foo.hasOwnProperty('bar') implies 'bar' in foo
  • typeof foo.bar != "undefined" implies 'bar' in foo
  • But those are the only inferences you can draw; no other implications are universally true, as the above counterexamples show.



回答2:


These are all different:

  1. foo.hasOwnProperty('bar') tells you whether foo has the property and does not perform lookup along the prototype chain.

  2. 'bar' in foo checks the prototype chain and returns true when it finds property bar in any object along the chain.

  3. typeof foo.bar != 'undefined' returns true if foo or any object along its prototype chain has property bar and it's value is not undefined.

Here is an example that demonstrates these differences:

var foo1 = { 'bar1': 10, 'bar2': undefined };
function ctor() {}
ctor.prototype = foo1;
var foo2 = new ctor();
foo2.bar3 = 20;

console.log(foo2.hasOwnProperty('bar1')); // false
console.log(foo2.hasOwnProperty('bar2')); // false
console.log(foo2.hasOwnProperty('bar3')); // true
console.log(foo2.hasOwnProperty('bar4')); // false

console.log('bar1' in foo2); // true
console.log('bar2' in foo2); // true
console.log('bar3' in foo2); // true
console.log('bar4' in foo2); // false

console.log(typeof foo2.bar1 != 'undefined'); // true
console.log(typeof foo2.bar2 != 'undefined'); // false
console.log(typeof foo2.bar3 != 'undefined'); // true
console.log(typeof foo2.bar4 != 'undefined'); // false



回答3:


one difference is that, method 1 will check only foo object for property bar while the last two methods will also check the prototype for inherited property.




回答4:


There are indeed some subtle differences between the various methods/keywords.

  1. foo.hasOwnProperty('bar') returns true only if the property 'bar' is defined on the foo object itself. Other properties, such as 'toString' will return false however since they are defined up the prototype chain.

  2. The in keyword operator returns true if the specified property is in the specified object. Both 'bar' in foo and 'toString' in foo would return true.

  3. Since you are checking for the state of the property, the result will be true when bar is not defined on foo and when bar is defined but the value is set to undefined.




回答5:


'bar' in foo 

will look anywhere up the prototype chain. Testing to see if foo.bar !== undefined will also return true if bar is anywhere in foo's prototype chain, but remember if bar is defined on foo, and set to undefined, this will return false.

hasOwnProperty is more choosy - it will only return true is bar is defined as a direct property of foo.

Per MDN

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.




回答6:


To add to what others have said, if you just want to know if a property exists and has a non-falsey value (not undefined, null, false, 0, "", NaN, etc...), you can just do this:

if (foo.bar) {
     // code here
}

As long as falsey values are not interesting to you for your particular circumstance, this shortcut will tell you if the variable has been set to something useful for you or not.

If you want to know if the property exists on the object in any way, I find this the most useful, brief and readable:

if ('bar' in foo) {
    // code here
}

One can also use something similar on function arguments (again as long as a falsey value isn't something you care about):

function foo(bar) {
    if (bar) {
        // bar was passed and has some non-falsey value
    }
}


来源:https://stackoverflow.com/questions/8539921/javascript-is-a-member-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!