犀牛——第6章对象 6.3删除属性

来源:互联网 发布:vscode 大小写快捷键 编辑:程序博客网 时间:2024/05/17 04:43

6.3 删除属性

delete运算符可以删除对象的属性。

例子:

delete book.author;   //book不再有属性author

delete book["main title"]   //book也不再有属性“main title”

当delete表达式删除成功或没有任何副作用时,它返回true。

delete只能删除自有属性,不能删除继承属性

例子:

o = {x:1};  //o有一个属性x,并继承属性toString

delete o.x;   //删除x,返回true

delete o.x;   //什么都没做(x已经不存在了),返回true

delete o.toString; //什么也没做(toString是继承来的),返回true

delete 1;           //无意义,返回true

6.4 检测属性

判断某个属性是否存在于某个对象中。可以通过in运算符、hasOwnPreperty()和propertyIsEnumerable()方法来完成这个工作,甚至仅通过属性查询也可以做到这一点。

in运算符的左侧是属性名,右侧是对象。

var o = {x:1}

"x" in o;    //true

"y" in o;    //false

"toString" in o; //true

对象的hasOwnProperty()方法用来检测给定的名字是否是对象的自由属性。对于继承属性它将返回false:

var o = {x:1}

o.hasOwnProperty("x");  //true:o有一个自有属性x

o.hasOwnProperty("y");  //false:o中不存在属性y

o.hasOwnProperty("toString");  //false:toString是继承属性

propertyIsEnumerable()是hasOwnProperty()的增强版,只有检测到是自有属性且这个属性的可枚举性为true时它才返回true。

var o = inherit({y:2});

o.x = 1;

o.propertyIsEnumerable("x");  //true:o有一个可枚举的自有属性x

o.propertyIsEnumerable("y");  //false:y是继承来的

Object.prototype.propertyIsEnumerable("toString");  //false:不可枚举

除了使用in运算符之外,另一种更简便的方法是使用“!==”判断一个属性是否是undefined:

var o = {x:1}

o.x !== undefined;   //true:o中有属性x

o.y !== undefined;   //false:o中没有属性y

o.toString !== undefined;  //true:o继承了toString属性










0 0
原创粉丝点击