class User {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
var u = new User('Jack')
u.getName()
"Jack"
es5写法
function User(name) {
this.name = name
}
User.prototype.getName = function getName() {
return this.name
}
var u = new User('Mary')
u.getName()
"Mary"
注: 若写为匿名函数,
User.prototype.getName = function () {
return this.name
}
常见错误写法!
function User(name) {
this.name = name
const _this = this
this.getName = function getName() {
return _this.name
}
}
var u = new User('Lucy')
u.getName()
区别在于keys
Object.keys(u)
(2) ["name", "getName"]
// 正确
Object.keys(u)
["name"]