javascript - 如何在 JavaScript 中重写私有(private)方法?

标签 javascript inheritance overriding prototype

我正在尝试使用 javascript 对象继承,其中我重写基“类”中的“私有(private)”方法(换句话说,使其成为 protected 方法)。

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

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

最佳答案

您可以引入一种可以更改私有(private)方法的特权方法:

// 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();

关于javascript - 如何在 JavaScript 中重写私有(private)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41819480/

相关文章:

Javascript函数无法触发onclick

javascript - 在 Angular 2 Google map 上移动 map 控件

c++ - 派生类忽略基类函数

java - Servlet 继承以及全局对象创建和访问

java - 我的代码请求抛出异常,但是当我这样做时,它说不应抛出异常

java - Maven第一次提示@Override注解,但下次编译成功

javascript - 如何根据类 jquery 回调函数更改单个元素?

javascript - Angular - For 循环 HTTP 回调/ promise

python - 在 Python 中使用泛型动态键入子类

java - 重写的方法不会抛出异常