JS对象初识 | 青训营笔记

86 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 6 天

前言

今天学习了JS对象的初级知识,主要有:

  • 什么是JS对象,以及如何声明
  • 对 this 关键字的理解
  • 了解对象的显示

一. 什么是对象?

所有 JavaScript 值,除了原始值,都是对象
而 JavaScript 中的变量是能容纳数据值的容器,对象也是变量,但却可以包含更多的属性。
这些属性被写成 name : value 的形式
方法是储存为对象属性的函数

const person = { 
  firstName: "John",      // 属性
  lastName : "Doe",  
  id       : 5566, 
  fullName : function() { // 方法
    return this.firstName + " " + this.lastName;
  }
};

1. 对this认识

this 是一个关键字,它代表一个对象,随着函数使用场合的不同,它指代的对象也随之不同

  • 在对象的方法中, this 指的是调用了这个方法的对象
  • this 单独使用时,指的是全局对象,这是因为 this 此时在全局范围内运行。
  • 在函数中, this 指的是也全局对象,但在函数的严格模式下, this 变为 undefined,
    这是因为严格模式不允许默认绑定。
  • 在事件中, this 指的是接收到事件的元素。
let x = this;    // 在浏览器窗口中,全局对象是 [object Window]

function myFunction() { 
  return this;   // [object Window]
}

"use strict";
function myFunction() { 
  return this;   // undefined
}

<button onclick="this.style.display='none'">Click to Remove Me!</button>

2. 对象的创建

  • 字面量
  • 关键字 new
  • 构造函数
// 字面量
const person = { 
  firstName: "John",      // 属性
  lastName : "Doe",  
  fullName : function() { // 方法
    return this.firstName + " " + this.lastName;
  }
};

// 关键字 new
const person = new Object(); 
person.firstName = "John";
person.lastName = "Doe";

// 构造函数
function Person(firstName,lastName) {
  this.firstName = firstName,      // 属性
  this.lastName = lastName,  
  this.fullName = function() { 
    return this.firstName + " " + this.lastName;
  }
}
var John = new Person("John","Doe");

对象是可变的:它们通过引用寻址,而不是值寻址。
这就表示,如果两个变量引用同一个对象,那么任何一方的修改都会使得同一个对象相应变化

const person = { 
  firstName:"John",
  lastName:"Doe",
  age:50, eyeColor:"blue"  
}

const x = person; 
x.age = 10;      // peison.age 也修改成 10

二. 如何显示一个对象

1. 循环访问对象的属性

const person = {
  name: "John",
  age: 30,
  city: "New York"
};

let txt = "";
for (let x in person) {
  txt += person[x] + " ";
};

2. Object.values() 转换成数组

任何 JavaScript 对象都可以使用 Object.values() 转换为数组。

const person = { 
  name: "John",  
  age: 30,  
  city: "New York"
};

const myArray = Object.values(person);

3. JSON.stringify() 转换成字符串

任何 JavaScript 对象都可以使用 JavaScript 函数 JSON.stringify() 转换为字符串。

const person = { 
  name: "John",  
  age: 30,  
  city: "New York" 
};

let myString = JSON.stringify(person);