当前位置:  开发笔记 > 编程语言 > 正文

JavaScript - 确定属性是否已定义并设置为"未定义"或未定义

如何解决《JavaScript-确定属性是否已定义并设置为"未定义"或未定义》经验,为你挑选了2个好方法。

说我有以下代码:

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

function Two() {}

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

o.x并且t.x都会评估undefined.o.hasOwnProperty('x')并且t.hasOwnProperty('x')都会返回虚假; 同样的道理propertyIsEnumerable.两个问题:

有没有办法告诉牛被定义并设置为undefined

有没有理由?(两者在语义上应该是等价的吗?)

一个小警告:在o中执行(对于propName)循环将产生'x'作为字符串之一,而在t中执行则不会 - 因此它们在内部表示的方式存在差异(至少在Chrome中).



1> Greg..:

比您的方法稍微简单的方法是使用Javascript in运算符

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


ECMAScript标准中的`in`关键字是什么?它是在Gecko和Webkit中实现的,但我不知道是否总能依赖它存在.

2> some..:

object.hasOwnProperty(name)仅对同一对象中的对象返回true,对其他所有对象返回false,包括原型中的属性.

function x() {
  this.another=undefined;
};

x.prototype.something=1;
x.prototype.nothing=undefined;
y = new x;

y.hasOwnProperty("something"); //false
y.hasOwnProperty("nothing"); //false
y.hasOwnProperty("another"); //true

"someting" in y; //true
"another" in y; //true

另外,删除属性的唯一方法是使用delete.将其设置为undefined不要删除它.

做正确的方法是用像roborg说.

更新: undefined是原始值,请参阅ECMAScript语言规范部分4.3.2和4.3.9.

推荐阅读
mobiledu2402852357
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有