<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
/* 1.属性的类型
数据属性
访问器属性
*/
/* 数据属性--
[Configurable]是否可删除并重新定义,是否可以修改他的特性,
[Enumberable]是否可以 for-in循环返回,
[Writable]是否可以被修改
[Value]包含属性的实际值 */
let person = {}
Object.defineProperty(person,"name",{
writable: false,
value: "Nicjoles"
});
console.log(person.name); // Nicjoles
person.name = "Greg";
console.log(person.name); // Nicjoles
// 证明没有被修改成功
/* 访问器属性--
[Configurable]是否可删除并重新定义,是否可以修改他的特性,
[Enumberable]是否可以 for-in循环返回,
[Get]获取函数,在读取属性时调用
[Set]设置函数,在写入属性时调用 */
let book = {
year_:2017,
edition: 1
};
Object.defineProperty(book,"year",{
get() {
return this.year_;
},
set(newValue) {
if(newValue > 2017) {
this.year_ = newValue;
this.edition += newValue - 2017;
}
}
});
book.year = 2018;
console.log(book.edition); // 2
/*
2.合并对象
Object.assign() 可合并一个或多个对象,并返回,不影响原对象
实际上对源对象执行的是潜复制
浅复制意味着只会复制对象的引用*/
let dest, src, result;
dest = {};
src = {
id: 'src'
};
result = Object.assign(dest, src);
console.log(result); // Object { id: "src" }
/*
3.对象解构
*/
// 不使用对象解构
let person2 = {
name: 'mack',
age: 12
}
let personName = person2.name,
personAge = person2.age;
//使用对象解构
let { name: personName2, age: personAge2 } = person2;
console.log(personName2); // mack
console.log(personAge2); // 12
// 或者提前声明变量
let personName3, personAge3;
({ name: personName3, age: personAge3 } = person2);
// 注意(源对象的修改,会影响新对象)
// 部分解构出错,会影响后续的解构
/*
4.构造函数模式
--构造函数也是函数,任何函数只要使用new操作符调用就是构造函数,而不使用new操作符调用的函数就是普通函数
--函数声明function Person(){}
--函数表达式let Person = function(){}
*/
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function() {
console.log(this.name);
}
}
// 在另一个对象的作用域中调用
// 将特定对象指定为作用域,这里的调用将对象o指定为Person()内部的this值,因此执行完函数后,所有属性和sayName()方法都会添加到对象o上面
let o = new Object();
Person.call(o, "nike", 25, "web");
o.sayName();
/*
5.对象迭代
----Object.values() 返回对象值的数组
----Object.entries() 返回键、值对的数组
注意:非字符串属性会被转换为字符串输出,另外,这两个方法执行对象的浅复制
*/
const o5 = {
foo: 'baz',
age: 12,
qux: {}
}
console.log(Object.values(o5)); // Array(3) [ "baz", 12, {} ]
/*
0: Array [ "foo", "baz" ]
1: Array [ "age", 12 ]
2: Array [ "qux", {} ]
length: 3
*/
console.log(Object.entries(o5));
</script>
</body>
</html>