说我有以下代码:
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中).
比您的方法稍微简单的方法是使用Javascript in运算符
alert('x' in o); // true alert('x' in t); // false
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.