繁体   English   中英

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

[英]How to override a private method in javascript?

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

可能吗? 这是我的最佳尝试(无效)

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

您可以引入一种特权方法,该方法可以更改私有方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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