提问人:ritwick_ _D 提问时间:11/11/2022 最后编辑:chrslgritwick_ _D 更新时间:11/15/2022 访问量:35
为什么在调用 Javascript 中的类声明中声明的方法时需要“this”关键字?[复制]
Why is `this` keyword necessary in calling methods declared in Class declarations in Javascript? [duplicate]
问:
这个问题在这里已经有答案了:
“this”关键字是如何工作的,何时应该使用? (22 个答案)
如何在回调中访问正确的“this” (15 个答案)
去年关闭。
这篇文章是去年编辑并提交审核的,但未能重新打开该帖子:
原始关闭原因未解决
在 MDN 文档中,
当调用静态或原型方法时没有 的值 ,例如将方法分配给变量然后调用它,则该值在方法内部将未定义。this
this
class Animal {
speak() {
return this;
}
static eat() {
return this;
}
}
const obj = new Animal();
obj.speak(); // the Animal object
const speak = obj.speak;
speak(); // undefined
Animal.eat() // class Animal
const eat = Animal.eat;
eat(); // undefined
我不明白当我们保存对变量的正常/静态方法引用时,为什么我们会丢失 的引用?this
此外,speak() 就像一个普通的类方法。在上面的文字中,这个方法是一个原型方法吗?
作为解决方案,它写道:
如果我们在非严格模式下使用传统的基于函数的语法重写上述内容,则此方法调用会自动绑定到初始 this 值,默认情况下该值是全局对象。在严格模式下,不会发生自动绑定;的值保持传递。
this
以及作为解决方案提供的代码:
function Animal() { }
Animal.prototype.speak = function () {
return this;
}
Animal.eat = function () {
return this;
}
const obj = new Animal();
const speak = obj.speak;
speak(); // global object (in non–strict mode)
const eat = Animal.eat;
eat(); // global object (in non-strict mode)
“ 那么这个方法调用会自动绑定到初始的 this 值,默认情况下是全局对象。” - this 方法调用发生在哪一行?
链接 : MDN Docs 链接
答: 暂无答案
评论
this
this
obj.speak()
obj
.speak()