“this”的值是用作事件处理程序的 Javascript 原型函数内部
我正在尝试在 Javascript 中使用原型继承。我下面的代码的问题是,当单击按钮并调用 MyNamespace.MyObj.myEventHandler
时,this
的值不是 MyNamespace 的实例。 MyObj
,而是被单击的按钮。
我的结构是否错误(有更好的方法)吗?我能否以某种方式确保 this
是对象的实例而不是调用者按钮?
var MyNamespace.MyObj = function(myform) {
this.myform = myform;
jQuery('.mybutton', this.myform).click(this.myEventHandler);
};
MyNamespace.MyObj.prototype = {
myEventHandler: function() {
this.myform.get(0).submit();
}
};
jQuery(document).ready(function() {
new MyNamespace.MyObj(jQuery('#myform'));
});
这只是一个非常简单的例子,我用它来学习原型继承。我意识到上述代码的实际功能可以简单地在 jQuery 中完成,或者我可以使用对象文字或模块模式 - 但我现在真的只是对学习原型继承感兴趣,而不是实现特定的功能。
I'm trying to use prototype inheritance in Javascript. The problem with my code below is that when the button is clicked and MyNamespace.MyObj.myEventHandler
is called, the value of this
is not the instance of MyNamespace.MyObj
, but is instead the button that was clicked.
Am I structuring things wrong (is there a better way)? Can I somehow ensure that this
is the instance of the object rather than the caller button?
var MyNamespace.MyObj = function(myform) {
this.myform = myform;
jQuery('.mybutton', this.myform).click(this.myEventHandler);
};
MyNamespace.MyObj.prototype = {
myEventHandler: function() {
this.myform.get(0).submit();
}
};
jQuery(document).ready(function() {
new MyNamespace.MyObj(jQuery('#myform'));
});
This is just a very dumbed down example that I'm using to learn prototype inheritance. I realize the actual function of the above code could be done simply in jQuery or that I could use an object literal or the Module pattern -- but I'm really just interested in learning the prototype inheritance rather than implementing a specific function at this time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有权访问* es5
Function.prototype.bind
,您可以执行以下操作:jQuery 提供
jQuery.proxy
,它执行相同的操作,但使用不同的语法:这两者都使用方法和对象,并返回一个将在该对象上调用该方法的函数。
当您在 JavaScript 中传递(或分配)一个方法时,它会从原始对象中切掉。这只是您必须了解的事情之一。 (实际上,这与使继承发挥作用是一样的。方法从父级中分离出来,并在子级的上下文中调用。)
*比如说,通过 es5 垫片。
If you have access* to the es5
Function.prototype.bind
, you can do this:jQuery provides
jQuery.proxy
, which does the same thing, but with different syntax:Both of these work with a method and an object, and return a function that will call that method on that object.
When you pass (or assign) a method in javascript, it gets sliced off of the original object. This is just one of those things you have to know. (This is the same thing that makes inheritance work, actually. Methods get sliced off of the parent, and are invoked in the context of the child.)
*Say, via the es5 shim.
有多种方法可以保存
this
值,最简单的 IMO 是:There are various ways to preserve the
this
value, the most simple IMO is: