Javascript redefine and override existing function body

后端 未结 8 2055
难免孤独
难免孤独 2020-12-24 03:12

I am wondering can we still change the function body once it is constructed ?

     var O = function(someValue){
           this.hello = function(){
                 


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-24 04:02

    No. You cannot, but here is a good example of ways around that limitation by patterning your inheritance in a different way.

    JavaScript override methods

    // Create a class
    function Vehicle(color){
      this.color = color;
    }
    
    // Add an instance method
    Vehicle.prototype.go = function(){
      return "Underway in " + this.color;
    }
    
    // Add a second class
    function Car(color){
      this.color = color;
    }
    
    // And declare it is a subclass of the first
    Car.prototype = new Vehicle();
    
    // Override the instance method
    Car.prototype.go = function(){
      return Vehicle.prototype.go.call(this) + " car"
    }
    
    // Create some instances and see the overridden behavior.
    var v = new Vehicle("blue");
    v.go() // "Underway in blue"
    
    var c = new Car("red");
    c.go() // "Underway in red car"
    

提交回复
热议问题