Cla*_*diu 37 javascript properties object undefined
说我有以下代码:
function One() {}
One.prototype.x = undefined;
function Two() {}
var o = new One();
var t = new Two();
Run Code Online (Sandbox Code Playgroud)
o.x并且t.x都会评估undefined.o.hasOwnProperty('x')并且t.hasOwnProperty('x')都会返回虚假; 同样的道理propertyIsEnumerable.两个问题:
undefined?一个小警告:在o中执行(对于propName)循环将产生'x'作为字符串之一,而在t中执行则不会 - 因此它们在内部表示的方式存在差异(至少在Chrome中).
Gre*_*reg 66
比您的方法稍微简单的方法是使用Javascript in运算符
alert('x' in o); // true
alert('x' in t); // false
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
另外,删除属性的唯一方法是使用delete.将其设置为undefined不要删除它.
做正确的方法是用在像roborg说.
更新: undefined是原始值,请参阅ECMAScript语言规范部分4.3.2和4.3.9.