在下面的代码中,我需要调用" private"子类run
Worker
function Person(scope, ...) {
scope.name = "Juan";
var run = function() {
console.log(scope.name + " is running");
};
}
function Worker(scope, ...) {
Person.call(this, scope, ...);
var jumpAndRun = function() {
console.log(scope.name + " is jumping");
run(); // how to call this
};
}
Worker.prototype = Object.create(People.prototype);
目前,如果我调用run
方法,我会获得Error: run is not defined!
答案 0 :(得分:3)
很抱歉,除非People
类(应该称为Person
)使该方法可用,否则无法执行此操作。
一种常见的做法是使私人"私人"方法以下划线开头。它不会100%授予任何安全性,但它至少会给其他开发人员一个暗示它是私有的暗示。
function Person(scope, ...) {
scope.name = "Juan";
var run = function() {
console.log(scope.name + " is running");
};
this._run = run;
}
function Worker(scope, ...) {
Person.call(this, scope, ...);
var jumpAndRun = function() {
console.log(scope.name + " is jumping");
this._run(); // how to call this
};
}