创建对象的方式
构造函数(不推荐) |
字面量(推荐) |
var object = new Object(); |
var object = {}; |
var array = new Array(); |
var array = []; |
var regExp = new RegExp("[a-z]", "g"); |
var regExp = /[a-z]/g; |
var s = new String(); |
var s = ""; |
var number = new Number(); |
var number = 0; |
var b = new Number(); |
var v = false; |
throw new Error("un-oh"); |
throw { name: "Error", message: "uh-oh" } |
构造函数创建
<script type="text/javascript">
var object = new Object();
object.name = "Locy";
object.age = 18;
object.say = function () {
return "I am " + this.name;
};
/**
* 对象属性如果赋值的是一个函数,在调用时不加 "()",
* 打印的是函数的定义语句,加上 "()" 打印的是函数的返回值
*
*/
object.say();
</script>
字面量创建
<script type="text/javascript">
var object = {
name: "Locy",
age: 18,
say: function () {
return "I am " + this.name;
}
};
object.say();
</script>
添加删除对象属性
- 对象属性不一定必须在定义对象时添加,在定义对象之后依然可以动态添加
- 为对象添加一个
sex
属性:object.sex = "M";
- 删除
name
属性:delete object.name;