javascript面向对象编程
2020年5月26日大约 2 分钟约 619 字
定义对象
Javascript对象是用字典来描述的:
// 定义对象
const person = {
// 定义属性
id: 12,
name: '张三',
age: 35,
sex: '男',
city: "成都",
// 定义函数
changeId: function(value){ this.id = value },
// 定义计算属性
get birthyear() {
return new Date().getFullYear() - this.age
},
set ageByBirthyear(year) {
this.age = new Date().getFullYear() - new Date(year.toString()).getFullYear()
}
}
// 访问对象
person.birthyear
person['age']
person.changeId(15)
// 对象转数组
const mykeys = Object.keys(person) // 属性转数组
const myValues = Object.values(person) // 值转数组
// 对象转JSON字符串
let myString = JSON.stringify(person)
- 这里的
this
指拥有changeId
函数的person
对象自己 - 箭头函数没有自己的
this
,不适合用于定义对象的方法
对象简写
有时候你会看到{ name, age }
这种语法,其实是对象的简写而已
const name = '张三'
const age = 18
const person = { name, age } // 如果对象的key的值和变量名相同就可以使用简写
console.log(person.name, person.age)
对象构造器
function Person(name, age) {
this.name = name // 这里this目前还没有值,它指向未来的新对象
this.age = age
this.changeAge = function(age) { this.age = age }
}
// 创建一个对象
const person1 = new Person('张三', 18)
- 构造器函数的命名首字母应大写
使用类创建对象
// 创建类
class Person {
// 构造函数
constructor(name, age) {
this.name = name
this.age = age
}
changeAge(age) {
this.age = age
}
}
// 继承类
class Women extends Person {
constructor(name, age) {
super(name, age) // 调用父级构造函数
this.sex = '女'
}
showSex() { return this.sex }
}
// 创建对象
let Person1 = new Women('孙尚香', 18)
- JS的类不是对象,只是对象的模板
this
精讲
this
指的是它所引用的对象,具体取决于它的使用位置:
在独立使用时,拥有者是全局对象,
this
指向的是全局对象在函数中使用,函数的拥有者是全局对象,
this
指向的是全局对象在严格模式下的函数中使用,
this
指向的是undefined
"use strict" function myFunction() { return this } // 返回为undefined
在方法中,
this
指向拥有该方法的对象本身在事件中,
this
指向的是接收事件的元素<button onclick="this.style.display='none'">点击删除我</button>
综合的说,
this
指使用该函数的对象
call()
和 apply()
这样的方法可以将 this 引用到任何对象:
let person1 = {
name: '张三',
lookName: function() { return this.name }
}
let person2 = { name: '李四' }
person1.lookName.call(person2) // 会返回'李四'
person1.lookName.apply(person2) // 与call功能相同,只是apply用数组接收参数