JavaScript对象
JavaScript也是面向对象的,构建对象也是十分简单,使用一个大括号加键值对来构造对象:
const man = {
firstName: "刘",
lastName: "玄德",
birthday: 1991,
job: "老师",
friends: ["张翼德", "关云长", "赵子龙"]
};
访问对象的属性时可以使用.(Dot)成员名进行访问,也能使用[]进行访问,如下所示:
console.log(man.job); // 老师
console.log(man["job"]); // 老师
console.log(man.job === man["job"]); // true
对象的键名也能是数字,但是此时对成员变量的访问只能采用中括号的形式,中括号内也可以使用表达式,示例如下:
const keyMap = {
0: 0,
1: 1,
10: 2,
11: 3
}
console.log(keyMap[11]); // 3
console.log(keyMap[10 + 1]); // 3
JavaScript的对象内部也可以定义函数,在前文就讲到,JavaScript中的所有函数都属于一种function数据结构,但是注意!!!对象内部的函数声明无法使用声明式定义方法,只能采用表达式和箭头式声明,示例如下:
const man = {
firstName: "刘",
lastName: "玄德",
birthday: 1991,
job: "老师",
friends: ["张翼德", "关云长", "赵子龙"],
helloStr: "Hello!",
calcAge: function () {
this.age = 2022 - this.birthday; // 计算结果直接存储到对象中,避免多次计算
console.log(this); // man
return this.age;
},
sayHello: () => {
console.log(this);
return this.helloStr; // undefined
},
getSummary: function () {
return `${this.firstName + this.lastName}今年${this.calcAge()}岁有${this.friends.length}个朋友,他最好的朋友叫${this.friends[0]}!`;
},
};
特别注意!!!虽然使用表达式函数和箭头函数都能在对象内部进行函数声明,但是这两种方式声明的函数的this指代对象不同。前者指向的是对象本身,后者指向的上一层作用域的this。
在上面的示例中sayHello函数使用箭头函数的方式进行定义,因此它的this指向的是window,所以访问不到对象内部的元素helloStr,输出的结果是undefined,但是如果我们需要在对象的函数的内部定义函数,如果我们希望使用到该对象的变量空间我们有两个解决办法,在ES6之前我们可以使用self来保存当前对象的this。
calcAge: function () {
const self = this;
self.age = 2022 - self.birthday; // 计算结果直接存储到对象中,避免多次计算
function sayAge() {
console.log(`Age is: ${self.age}`);
}
sayAge();
},
还能使用箭头函数,此时使用箭头函数this指向的就是上层function的this了:
calcAge: function () {
const self = this;
self.age = 2022 - self.birthday; // 计算结果直接存储到对象中,避免多次计算
const sayAge = () => {
console.log(`Age is: ${self.age}`);
}
sayAge();
},
同样JavaScript的函数的参数的规则对于正常函数和箭头函数也是不同的,正常函数可以传递比声明数量更多的参数,而箭头函数不行,且实参的数量少于形参的数量,多余的形参会被定义为 undefined,反之多余的实参也没有形参与之对应。函数的参数列表我们可以使用arguments关键字查看,函数的arguments关键字是一个对象,可以用其遍历所有传入的参数。示例如下:
let add = function (a, b) {
console.log(typeof arguments);
for (let index = 0; index < arguments.length; index++) {
const element = arguments[index];
console.log(element);
}
return a + b;
}
add(1, 2, 3, 4, 5);
/*
object script.js:69:13
1 script.js:72:17
2 script.js:72:17
3 script.js:72:17
4 script.js:72:17
5 script.js:72:17
*/
因此在实际开发过程中使用arguments要慎重,经量不要使用。