简体   繁体   中英

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

How to protect a public method to be overrided by a chield object in javascript?

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

Chield 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

The "move*" methods can't be overrided by chield class!

Any tip?

You can declare a property as readonly . Readonly properties cannot be overwritten. Example:

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

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

However, overriding the property will silently fail, it won't throw an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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