简体   繁体   中英

javascript: How to override a method for all the instances of some class?

function Person(){
    this.scream = function(){
        alert('NO NO NO!!!!');
    };
}

var steve = new Person();
steve.scream() // NO NO NO!!!!
Person.prototype.scream = function(){
    alert('YES YES YES!!!!');
}
steve.scream() // still NO NO NO!!!!

Is there a way to override ' scream ' without referencing steve explicitly? Think about the cases when you have may instances of Person .

No,

Having that Person declaration, every time you create a new "instance" of it the "constructor" will run and you'll create a completely new scream function (closure) which you don't have any reference to, except from the newly created object, steve.scream that is.

As an alternative you may do it like this:

function Person(){}

Person.prototype.scream = function(){
    alert('NO NO NO!!!!');
}

var steve = new Person();
steve.scream() // NO NO NO!!!!
Person.prototype.scream = function(){
    alert('YES YES YES!!!!');
}
steve.scream() // this time is YES YES YES!!!!

In which case the initial scream "method" is available only in one place, on the prototype, and you can overwrite it for all "instances".

function Person(){};
Person.prototype.scream = function(){ alert('NO NO NO!!!!'); };
var steve = new Person();
steve.scream();
Person.prototype.scream = function(){alert('YES YES YES!!!!');};
steve.scream();

and, if you want to continue to use your code style, you may like

function Person(){
    this.constructor.prototype.scream = function(){
        alert('NO NO NO!!!!');
    };
}
var steve = new Person();
steve.scream();
Person.prototype.scream = function(){ alert('YES YES YES!!!!'); };
steve.scream();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM