- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我理解以下代码片段中发生的事情,以及如何修复(使用绑定(bind)或通过构造函数之外的方法使 walk friend),但为什么会发生这种情况?必须将类的作用域绑定(bind)到它自己的方法对我来说似乎违反直觉。
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.'
最佳答案
发生的事情是 ES2015(“ES6”)类中的“方法”与实例之间没有内在联系,就像旧式构造函数没有内在联系一样。¹ friend.walk
只是返回一个原始方法引用,没有任何东西可以将它绑定(bind)到 friend
除非你自己这样做。换句话说,friend.walk === Person.prototype.walk
是 true
。例如,您的反直觉理解是正确的(除了它与范围无关,而是关于 this
的值)。 :-)
请记住,新的 class
内容几乎完全只是语法糖(但是,您知道,是一种很好的糖)。您的 Person
类几乎完全等同于此 ES5 代码:
var Person = function Person(name, friend) {
this._name = name;
if(friend) {
this.walkFriend = friend.walk;
}
};
Object.defineProperty(Person.prototype, "name", {
get: function() {
return this._name.toUpperCase();
},
configurable: true
});
Object.defineProperty(Person.prototype, "walk", {
value: function() {
console.log(this.name + ' is walking.');
},
writable: true,
configurable: true
});
你说过你知道如何解决它,事实上你的两个解决方案都可以工作,要么绑定(bind):
constructor(name, friend) {
this._name = name;
if(friend) {
this.walkFriend = friend.walk.bind(frield); // **
}
}
或者在构造函数中创建 walk
作为箭头函数,而不是在原型(prototype)上:
constructor(name, friend) {
this._name = name;
this.walk = () => { // **
console.log(this.name + ' is walking.'); // **
}; // **
if(friend) {
this.walkFriend = friend.walk;
}
}
¹ 在方法和定义它的类的原型(prototype)之间是一个内在联系,如果您使用super
方法中的关键字。链接方法的 [[HomeObject]] 字段的规范调用(但您不能在代码中访问它,如果您不使用 super
,它可以被 JavaScript 引擎优化掉在方法中)。
关于javascript - ES6 类中的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38613150/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!