我是一个刚刚学习 JavaScript 的 C++ 人员,因此“this”绑定到调用对象的事实仍然令人惊讶。我想使用对象方法作为事件侦听器,并希望确保我以 JavaScript 专业人士的所有风格来执行此操作。
因此,为了让该方法拥有其对象“this”,以便我可以在适当的上下文中访问其属性,我编写了以下内容:
var user =
{
status: 1, // login status: 0:invalid password, 1:logged out, 2:logged in
loginName: "",
// Method called whenever the user submits a username/password via html form:
onLoginSubmit: function (event)
{
if (this != user) // called from 'form submit' callback, so call ourselves:
{
user.onLoginSubmit(event);
return;
}
}
};
Run Code Online (Sandbox Code Playgroud)
我在这里找到了以前的答案:Accessing an object's property from an event Listener call in Javascript,但建议的解决方案基本上是创建一个全局的。有没有比以前的解决方案或我的递归解决方案更酷、更专业的方法来获得“这个”?
我必须错过关于emplace()和朋友的一个更好的观点.这是一个完整的,最小的例子,用g ++ 4.9.3重现问题:
class Foo
{
public:
class Bar
{
private:
friend class Foo;
Bar(Foo &foo) : foo(foo) {}
Foo &foo;
};
Bar &getBar()
{
//bars.push_back(*this); // works fine
bars.emplace_back(*this); // Foo::Bar::Bar(Foo&) is private
return bars.back();
}
private:
std::vector<Bar> bars;
};
Run Code Online (Sandbox Code Playgroud)