如何在javascript中覆盖私有方法?

时间:2017-01-24 03:22:07

标签: javascript inheritance override prototype

我试图使用javascript对象继承来覆盖" private"基地中的方法" class" (换句话说,使其成为受保护的方法)。

有可能吗?这是我最好的尝试(不起作用)

function Vehicle(color) {
    this.color = color;
}

Vehicle.prototype.drive = function() {
    _getMessage.call(this);
}

function _getMessage() {
    console.log("override this method!")
}


//----------------------------------------------------------------

var Car = (function() {

    Car.prototype = Object.create(Vehicle.prototype);
    Car.prototype.constructor = Car;

    function Car(color) {
        Vehicle.call(this, color)
    }

    function _getMessage() {
        console.log("The " + this.color + " car is moving!")
    }


    return Car;
}());

//----------------------------------------------------------------

$(function() {
    var c = new Car('blue');
    c.drive()

})

https://plnkr.co/edit/ZMB9izK1W9VuFQHPNsvu?p=preview

1 个答案:

答案 0 :(得分:2)

您可以引入可以更改私有方法的特权方法:

// IIFE to create constructor
var Car = (function(){

  // Private method
  function _getMessage(text){
    console.log('original: ' + text);
  }

  // Normal constructor stuff
  function Car(make){
    this.make = make;
  }
  Car.prototype.getMake = function(){
    return this.make;
  }
  Car.prototype.getMessage = function(){
    _getMessage(this.make);
  }

  // Privileged function to access & change private method
  Car.changeGetMessage = function(fn) {
    _getMessage = fn;
  }
  return Car;
}());

// Demonstration
// Create instance
var ford = new Car('Ford');
console.log(ford.getMake());

// Call original method
ford.getMessage();

// Replace original
Car.changeGetMessage(function(text){
  console.log('new message: ' + text);
});

// Existing instances get new method
ford.getMessage();

// Create new instance
var volvo = new Car('Volvo');
console.log(volvo.getMake());

// New instances get method too
volvo.getMessage();