1.?JS 对象
JS 对象是什么?
JS 对象就是一系列属性的集合,一个属性包含一个名和一个值。一个属性的值可以是函数,这种情况下属性也被称为方法。
JS 对象数据类型
在 JS 中,对象的类型是引用类型。
JS 对象的访问
不同于C++等其它语言,JS 对象全是 public。
2.?JS 对象的声明方法
这里介绍四种基础的声明方法:
let obj = {
name: 'milk',
getName: function() {
return this.name;
}
}
let obj = new Object();
obj.name = "milk";
function creatObj(nameVal) {
this.name = nameVal;
}
let obj = new createObj("milk");
function drinking() {};
drinking.prototype.name = "milk";
drinking.prototype.pride = 8;
let obj = new drinking();
console.log(obj.name);
3.?JS 对象中的this
在对象方法中, this 指向调用它所在方法的对象。 举个例子:
let person = {
fname: '序员',
lname: '程',
fullname: function() {
return this.lname + this.fname;
}
}
let get_full_name = person.fullname();
console.log(person.fullname());
console.log(get_full_name);
4.?一些常用的操作方法
4.1) Object.keys(obj), Object.getOwnPropertyNames(obj)
let drinking = {
name : "milk"
};
Object.defineProperty(drinking, "pride", {
value : 8,
enumerable : false
});
console.log(Object.keys(drinking));
console.log(Object.getOwnPropertyNames(drinking));
4.2) Object.values(obj)
let drinking = {
name : "milk",
pride : 8
}
console.log(Object.values(drinking));
4.3) Object.entries(obj), Object.fromEntries()
let drinking1 = {
name : "milk",
pride : 8
}
console.log(Object.entries(drinking1));
let arr = [['name', 'milk'], ['pride', 8]];
let drinking2 = Object.fromEntries(arr);
console.log(drinking2);
4.4) Object.assign()
let drinking1 = {
name1 : "milk",
pride1 : 8
};
let drinking2 = {
name2 : "tea",
pride2 : 12
};
let drinking = Object.assign(drinking1, drinking2);
console.log(drinking);
4.5) 扩展运算符
let drinking1 = {
name1 : "milk",
pride1 : 8
};
let drinking2 = {
name2 : "tea",
pride2 : 12
};
let drinking = {...drinking1, ...drinking2};
console.log(drinking);
4.6) 删除对象属性
let drinking = {
name : "milk",
pride : 8
};
delete drinking.pride;
console.log(drinking);
4.7) for…in遍历对象
let drinking = {
name : "milk",
pride : 8
};
for (i in drinking) {
console.log(i);
}
4.8) hasOwnProperty 检测属性
let drinking = {
name : "milk",
pride : 8
};
console.log(drinking.hasOwnProperty('name'));
console.log(drinking.hasOwnProperty('weight'));
|