保护 public 方法被 javascript 中的子 object 覆盖

Protect a public method to be overrided by a chield object in javascript

如何保护 public 方法被 javascript 中的子 object 覆盖?

Parent class:

var Robot = function (id) {

    this.id = id;
    this.x = 400;
    this.y = 300;
    this.name = "nameless";
    this.speed = 10;

};

Robot.prototype.onUpdate = function() {
    //Need to be overrided 
};

Robot.prototype.moveUp = function() {
    this.y-=this.speed;
};

Robot.prototype.moveDown = function() {
    this.y+=this.speed;
};

Robot.prototype.moveLeft = function() {
    this.x-=this.speed;
};

Robot.prototype.moveRight = function() {
    this.x+=this.speed;
};

Robot.prototype.moveRandom = function() {

    var low = 0;
    var high = 4;

    var directions = [this.moveUp,this.moveDown,this.moveLeft,this.moveRight];
    var direction = Math.floor(Math.random() * (high - low) + low);

    var move = directions[direction];
    move.call(this);

};

module.exports = Robot;

https://github.com/JoeLoco/robota/blob/master/lib/robot.js

孩子 class:

var Robot = require('../lib/robot.js');

var SampleRobot = function (id) {

    Robot.call(this,id);
    this.name = "Sample Robot";

};
SampleRobot.prototype = Object.create(Robot.prototype);

SampleRobot.prototype.onUpdate = function() {

    // Overrride the update event

    this.moveUp();

    console.log(this);

};


module.exports = SampleRobot;

https://github.com/JoeLoco/robota/blob/master/robots/sample-robot.js

"move*" 方法不能被孩子 class!

覆盖

有什么建议吗?

您可以将 属性 声明为 readonly。只读属性不能被覆盖。示例:

var parent = {};
Object.defineProperty(parent, 'test', {value: 42, readonly: true});

var child = Object.create(parent);
child.test = 21;
console.log(child.test); // 42;

但是,重写 属性 将默默地 失败,它不会抛出错误。