定义一个基础的类
class Person {
constructor(name = '杜恒') {
this.name = name
}
speak() {
console.log(this);
}
}
将上面的类实例出一个对象p,并调用p的speak方法
const p = new Person()
p.speak() // Person {name: "杜恒"}
尝试将p实例对象身上的speak方法赋值给另一个变量进行调用
const test = p.speak
test() // undefined
打印undefind,因此上面的方法可以改写成如下
const test = function () {
"use strict"
console.log(this);
}
test() // undefined
评论 (0)