如何在javascript中重写私有方法?

如何在javascript中重写私有方法?,javascript,inheritance,overriding,prototype,Javascript,Inheritance,Overriding,Prototype,我试图使用javascript对象继承,在这里我重写了基“类”中的“私有”方法(换句话说,使其成为受保护的方法) 可能吗?这是我最好的尝试(不起作用) 您可以引入一种特权方法来更改私有方法: //创建构造函数的生命 var Car=(函数(){ //私有方法 函数_getMessage(文本){ console.log('原始:'+文本); } //普通构造函数 多功能车(品牌){ make=make; } Car.prototype.getMake=函数(){ 把这个还给我; } Car.p

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

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


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

//创建构造函数的生命
var Car=(函数(){
//私有方法
函数_getMessage(文本){
console.log('原始:'+文本);
}
//普通构造函数
多功能车(品牌){
make=make;
}
Car.prototype.getMake=函数(){
把这个还给我;
}
Car.prototype.getMessage=函数(){
_getMessage(this.make);
}
//访问和更改私有方法的特权函数
Car.changeGetMessage=功能(fn){
_getMessage=fn;
}
返回车;
}());
//示范
//创建实例
var ford=新车(“福特”);
log(ford.getMake());
//调用原始方法
ford.getMessage();
//替换原来的
Car.changeGetMessage(函数(文本){
console.log('新消息:'+文本);
});
//现有实例获取新方法
ford.getMessage();
//创建新实例
var沃尔沃=新车(“沃尔沃”);
console.log(volvo.getMake());
//新实例也得到了方法

getMessage()您可以引入一个特权方法来更改私有方法:

//创建构造函数的生命
var Car=(函数(){
//私有方法
函数_getMessage(文本){
console.log('原始:'+文本);
}
//普通构造函数
多功能车(品牌){
make=make;
}
Car.prototype.getMake=函数(){
把这个还给我;
}
Car.prototype.getMessage=函数(){
_getMessage(this.make);
}
//访问和更改私有方法的特权函数
Car.changeGetMessage=功能(fn){
_getMessage=fn;
}
返回车;
}());
//示范
//创建实例
var ford=新车(“福特”);
log(ford.getMake());
//调用原始方法
ford.getMessage();
//替换原来的
Car.changeGetMessage(函数(文本){
console.log('新消息:'+文本);
});
//现有实例获取新方法
ford.getMessage();
//创建新实例
var沃尔沃=新车(“沃尔沃”);
console.log(volvo.getMake());
//新实例也得到了方法

getMessage()你不能这样做。另外,原始的
\u getMessage
函数实际上不是您的类的一部分。
这是我的最佳尝试(不起作用)
-它有什么问题?你期待什么?您得到的是什么?\u getMessage是全局的,它在任何方面都不是“私有的”,只需替换它即可。如果它实际上是私有的,如果你有专门的特权函数,你可以替换它。
\u getMessage
在你的
汽车中
对象是“私有的”,因为它只在该生命的范围内可见。。。除非你让它可用,否则再多的原型欺骗或更新的
甜善也不会让该函数在该范围之外可用,因此它不是“私有的”@JaromandaX,而是“私有的”\u getMessage永远不会被调用……那么有什么意义呢?;-)你不能这样。另外,原始的
\u getMessage
函数实际上不是您的类的一部分。
这是我的最佳尝试(不起作用)
-它有什么问题?你期待什么?您得到的是什么?\u getMessage是全局的,它在任何方面都不是“私有的”,只需替换它即可。如果它实际上是私有的,如果你有专门的特权函数,你可以替换它。
\u getMessage
在你的
汽车中
对象是“私有的”,因为它只在该生命的范围内可见。。。除非你让它可用,否则再多的原型欺骗或更新的
甜善也不会让该函数在该范围之外可用,因此它不是“私有的”@JaromandaX,而是“私有的”\u getMessage永远不会被调用……那么有什么意义呢?;-)
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()

})