在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 samplesubSample.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 的原型方法。 到此这篇关于在JavaScript 实例对象中改写原型方法详情的文章就介绍到这了,更多相关在JavaScript 实例对象中改写原型方法内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net! 下载地址: 如何让js中的if判断如丝般顺滑详解 JS实现旋转木马轮播案例 |