很抱歉,如果之前有人问过这个问题,但经过大量搜索后,我似乎找不到明确解决我的情况的答案。
我有一个父类(super class),我们称之为 Form,它有一些通用方法。我将只关注两种特定的方法。 show_form()
显示表单,load_token()
从服务器获取 token 。
表格
function Form() {
// Event handler for form submission
this.submit_button.bind('click', jQuery.proxy(function(){
this.submit();
}, this));
}
Form.prototype.show_form = function() {
// Some other stuff happens here, but this is the relevant part.
// We load the token
this.load_token();
}
Form.prototype.load_token = function(){
// Contains a synchronous ajax request that fetches the token from the server
// and sets it. So we end up with
this.token = 'some-token';
};
然后我有一个名为EmailForm的子类,它继承自Form。我还为此类定义了一个自定义 submit()
方法,该方法由 Form()
构造函数中的事件处理程序调用。所以我有:
电子邮件表单
function EmailForm() {};
EmailForm.prototype = new Form();
EmailForm.prototype.submit = function() {
console.log(this.token); // Returns undefined
};
最后,这就是这一切的结合方式
$('#email_form_link').bind('click', function(){
var email_form = new EmailForm();
email_form.show_form();
});
问题
所以我需要 token 来向服务器发出请求。由于多种表单需要 load_token() 方法,因此我在父类(super class)中定义它并让子类继承它。由于我调用 email_form.show_form()
,我希望 email_form
的 token
属性会被设置,但这似乎并没有就这样吧。
那么如何调用从父类(super class)继承的方法,并让它更改调用它的子类的属性呢?
最佳答案
您可以尝试使用 this
关键字而不是使用对象的 prototype
来定义方法。当然,这意味着每个新对象将获得它自己的方法实例(更多内存),而不是“继承”或共享相同的实例,但是这样,每个对象(EmailForm的子类)将拥有它自己的属性 token
设置。
例如。
关于JavaScript继承: Setting property of sub-class from method of super class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20104515/