【发布时间】:2016-07-27 12:35:01
【问题描述】:
我了解下面的 sn-p 中发生了什么,以及如何修复(使用绑定或通过使 walkfriend 成为构造函数之外的方法),但为什么会发生这种情况?将一个类的作用域绑定到它自己的方法对我来说似乎违反直觉。
class Person {
constructor(name, friend) {
this._name = name;
if(friend) {
this.walkFriend = friend.walk;
}
}
get name() {
return this._name.toUpperCase();
}
walk() {
console.log(this.name + ' is walking.');
}
}
let bob = new Person('Bob');
let bill = new Person('Bill', bob);
console.log(bob.name); // BOB
console.log(bill.name); // BILL
bill.walk() // Bill is walking.
bill.walkFriend(); // We expect 'BOB is walking', but we get 'BILL is walking.'
【问题讨论】:
标签: javascript class ecmascript-6