JavaScript 基础
Document
运算符
深入数据和类型
函数进阶
原型、继承
类
浏览器存储
Web API
事件
错误处理
异步编程
网络请求
模块
练习
实例
工具与规范
软件架构模式
设计模式
有关对象类型的初步学习请参考对象章节。
方法简写
我们一般称呼在对象中属性值为函数的属性为方法,我们在定义对象内方法时可以省略掉冒号与 function
关键字。这便是方法的简写。
$$jsdemo$$
$$edit$$
let person = {
name: "孙悟空",
// sayName 就是一个方法
sayName: function () {
alert("我叫孙悟空")
},
// 方法的缩写
sayHello() {
alert("你好呀")
},
}
person.sayName() // 调用对象的方法
person.sayHello() // 调用对象的方法
this 关键字
有时我们需要一个方法访问对象自身内部的属性,根据已学的知识我们会写成下面这样。
$$jsdemo$$
$$edit$$
let sunwukong = {
name: "孙悟空",
sayName() {
alert(sunwukong.name)
},
}
sunwukong.sayName() // 孙悟空
如果这样写,各个对象就得重写 sayName
方法。
$$jsdemo$$
$$edit$$
let sunwukong = {
name: "孙悟空",
sayName() {
alert(sunwukong.name) // 各不相同
},
}
let mingren = {
name: "鸣人",
sayName() {
alert(mingren.name) // 各不相同
},
}
sunwukong.sayName() // 孙悟空
mingren.sayName() // 鸣人
我们需要一种在方法内部访问自身所在函数的手段,于是 this
关键字出现了。
当 this
关键字处于方法中时,指向调用方法的对象。
$$jsdemo$$
$$edit$$
let sunwukong = {
name: "孙悟空",
showThis() {
console.log(this) // {name: '孙悟空', showThis: ƒ}
console.log(this === sunwukong) // true
},
}
sunwukong.showThis()
以下代码中 this
关键字分别指向调用自身方法的对象。
let sunwukong = {
name: "孙悟空",
sayName() {
alert(this.name) // this 指向 sunwukong
},
}
let mingren = {
name: "鸣人",
sayName() {
alert(this.name) // this 指向 mingren
},
}
sunwukong.sayName() // 孙悟空
mingren.sayName() // 鸣人
我们也可以将 sayName
方法抽出来,这样就不用重复写多次了。
$$jsdemo$$
$$edit$$
function sayName() {
alert(this.name)
}
let sunwukong = {
name: "孙悟空",
sayName,
}
let mingren = {
name: "鸣人",
sayName,
}
sunwukong.sayName() // 孙悟空
mingren.sayName() // 鸣人
如果一个函数未处于对象之中,则其中的 this
指向 window 对象。
$$jsdemo$$
$$edit$$
function test() {
console.log(this)
}
test() // Window
$$warning
避免出现在未绑定对象的函数中使用 this 的情况,这不符合编程思路,出现这种情况只能表明我们写错了代码。
$$
练习
- 补全以下代码。
function showInfo() {
// 补全代码
}
let mingren = {
name: "鸣人",
score: 50,
showInfo,
}
let kenan = {
name: "柯南",
score: 98,
showInfo,
}
mingren.showInfo() // 我叫鸣人,我考试没及格。
kenan.showInfo() //我叫柯南,我考试及格了。
$$answer
$$jsdemo$$
$$edit$$
function showInfo() {
if (this.score >= 60) {
alert(`我叫${this.name}, 我考试及格了。`)
} else {
alert(`我叫${this.name}, 我考试没及格。`)
}
}
let mingren = {
name: "鸣人",
score: 50,
showInfo,
}
let kenan = {
name: "柯南",
score: 98,
showInfo,
}
mingren.showInfo() // 我叫鸣人,我考试没及格。
kenan.showInfo() //我叫柯南,我考试及格了。
$$