简体   繁体   English

保护一个公共方法被javascript中的子对象覆盖

[英]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?如何保护一个公共方法被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 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 https://github.com/JoeLoco/robota/blob/master/robots/sample-robot.js

The "move*" methods can't be overrided by chield class! “move*”方法不能被子类覆盖!

Any tip?任何提示?

You can declare a property as readonly .您可以将属性声明为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.但是,覆盖该属性将无声地失败,它不会抛出错误。

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

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