在JavaScript中,我们通常可以像下面的代码这样来简单地定义一个类:
var sample = function() {
// constructor code here
}
sample.prototype.func1 = function() {
// func1 code here
}
sample.prototype.func2 = function() {
// func2 code here
}
/* more sample prototype functions here... */
然后使用下面的代码来实例化,并访问其中的原型方法:
var sampleInstance = new sample();
sampleInstance.func1();
sampleInstance.func2();
// call more sample object prototype functions
但是如果我们想改写其中一个原型方法,并且不破坏原有的sample对象,如何来实现呢?一个最简单的方法就是再构建一个类,使其继承sample,然后在继承类的原型方法中改写基类的方法,就像下面这样:
var subSample = function() {
// constructor code here
}
// inherit from sample
subSample.prototype = new sample();
subSample.prototype.fun1 = function() {
// overwrite the sample's func1
}
但是如果没有构建继承类,而想改写原型方法,可以直接使用下面的代码:
var sampleInstance = new sample();
sampleInstance.func1 = function() {
sample.prototype.fun1.call(this); // call sample's func1
// sampleInstance.func1 code here
}
我们重新定义了sample的实例对象的func1方法,并在其中访问了其原型方法func1,然后又在其中添加了一些额外代码。通过这样的方法,我们对sample的原型方法进行了扩展,并且没有创建派生类,而且也没有破坏sample的原型方法。