对象
var Amanda = {
name: "Amanda",
age : 25,
health : 100,
playTennis : function() {
console.log("Playing tennis");
this.health++;
},
drink : function() {
console.log("drinking");
this.health--;
}
}
- 增加和删除属性和方法
Amanda.gender = "female";
delete Amanda.gender;
对象的创建方法
- var obj = {}
plainObject 对象字面量/对象直接量 - 构造函数
- 系统自带的构造函数 new Object()
- 自定义构造函数
// 没有参数
function Car(){
this.name = "benz";
this.height = "1400";
this.length = "4900";
this.weight = 1000;
}
// 创建对象
var car1 = new Car();
// 有参数
function Student(name, age, gender){
this.name = name;
this.age = age;
this.gender = gender;
}
//创建对象
var student = new Student("xiaowang", 18, "female");
构造函数内部原理
- 在函数体最前面隐式的加上this={}
- 执行this.xxx=xxx;
- 隐式的返回this
包装类
// 包装类
var num = 4;
// 隐式创建一个Number对象
// new Number(4).len = 3;
// delete
num.len = 3;
// 再次创建一个Number对象
// new Number(4).len
console.log(num.len);
输出undefined
知识和示例来源:渡一