我正在尝试在原型(prototype)构造函数
中访问this
(我想这就是它的名字?)。
SomethingUseful.prototype = {
constructor: SomethingUseful,
init: init,
someFunction: someFunction,
mouseDownHandler: mouseDownHander.bind(this)
}
但是this
等于window
。所以我尝试做 bind(SomethingUseful)
,当我在 mouseDownHandler
中使用 this
时,整个函数以纯文本形式注销,所以我可以不要在实际的 mouseDownHandler
函数中使用 this
中的内容。
在 constructor
函数中访问 SomethingUseful
的 this
的正确方法是什么(同样,我可能把名字弄错了,如果我做了,请纠正它,或者在评论中让我知道)?
最佳答案
Instead of doing this:
this.mouseDownHandler = mouseDownHander.bind(this);
I want to add it inSomethingUseful.prototype = {
.
这是不可能的。当您尝试将函数绑定(bind)到实例时,没有可以将该函数绑定(bind)到的实例。只有在调用构造函数时或之后才会有一个实例来绑定(bind)该函数。
换句话说:您试图在披萨送达之前吃掉它。
<小时/>相关:How to access the correct `this` context inside a callback?
关于javascript - 在构造函数对象中访问 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41047711/