亲宝软件园·资讯

展开

JavaScript中对象介绍

人气:0

JavaScript中,除了number、string、boolean、null和undefined,其它所有的值都是对象。对象可以通过字面量来直接声明,也可以通过new操作符来新建。与Java语言不同,JavaScript对象中的property是可以动态添加或者删除的;同时,对象中的property还可以是空字符串:


复制代码 代码如下:

//properties in object can be addedhttps://img.qb5200.com/download-x/deleted dynamically
var o = {x:1, y:2};
console.log(o);//Object {x=1, y=2}
delete o.y;
o.z = 3;
console.log(o);//Object {x=1, z=3}

//empty string is allowed as object property
var o2 = {"":88, "p":99};
console.log(o2);//Object { =88, p=99}

//for constructor function, "new" operation returns an object.
function Computer(x, y) {
  this.x = x;
  this.y = y;
}
var c = new Computer(126, 163);
console.log(c);//Computer {x=126, y=163}
var c2 = new Computer(126);//missing parameter value will be "undefined"
console.log(c2);//Computer {x=126, y=undefined}
c.z = 66;
console.log(c);//Computer {x=126, y=163, z=66}
delete c.y;
console.log(c);//Computer {x=126, z=66}

如果在使用new操作符来新建对象时,作用的function并不是一个类的constructor,而仅仅是一个普通的函数,那么JavaScript将在执行该函数后返回一个空对象:

复制代码 代码如下:

//for pure function, "new" operation returns an empty object.
function compute(x){
  console.log("execute function compute");
  return x*2;
}
var a = new compute();
console.log(a);//compute {}

Object属性

JavaScript中的Object有以下3个属性:

1.prototype。引用,指向Object的原型对象。原型对象中的property可以被Object所继承。
2.class。字符串,表示Object的类名。
3.extensible。boolean值,表示Object中是否允许动态添加property。该属性仅在ECMAScript 5中有效。

Property属性

Object中的Property也有3个属性:

1.writable。该property是否可写。
2.enumerable。当使用for/in语句时,该property是否会被枚举。
3.configurable。该property的属性是否可以修改,property是否可以删除。

加载全部内容

相关教程
猜你喜欢
用户评论