这是一些应该可以工作的代码:
var BasicPage = function(){
this.name="BasicPage";
document.body.onclick=this._getClick(this);
};
BasicPage.prototype._getClick=function(me){
return function(e){
console.log("target is:,",e.target);
console.log("this is:",me.name);
}
};
var PageWithSections = function(){
//initialise parent and it's instance members
BasicPage.call(this);
//override name
this.name="PageWithSections";
};
PageWithSections.prototype=Object.create(BasicPage.prototype);
PageWithSections.prototype.constructor=PageWithSections;
var sect = new PageWithSections();
document.body.click();
以下代码演示了如何在不复制和粘贴已有的 BasicPage 代码的情况下扩展 onclick 处理程序:
var BasicPage = function(){
this.name="BasicPage";
document.body.onclick=this._getClick(this);
};
BasicPage.prototype._getClick=function(me){
return function(e){
console.log("re used code from BasicPage");
console.log("target is:,",e.target);
console.log("this is:",me.name);
}
};
var PageWithSections = function(){
//initialise parent and it's instance members
BasicPage.call(this);
//override name
this.name="PageWithSections";
};
//set prototype chain
PageWithSections.prototype=Object.create(BasicPage.prototype);
PageWithSections.prototype.constructor=PageWithSections;
//extend _getClick
PageWithSections.prototype._getClick=function(me){
var fn=BasicPage.prototype._getClick.call(me,me);
return function(e){
//do BasicPage click code
fn(e);
//extended code
console.log("with a little extra from PageWithSections");
};
};
var sect = new PageWithSections();
document.body.click();
更多关于原型和构造函数的信息在这里。介绍应该非常有帮助,如果您有时间,我建议您阅读所有内容以更好地理解 JS 原型。