[英]Call “private” method from “parent” object in javascript
in the following code, i need call the "private" method run
in the sub class Worker
在以下代码中,我需要调用在子类Worker
run
的“ private”方法
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);
currently if i call run
method i get an Error: run is not defined!
目前,如果我调用run
方法,则会收到Error: run is not defined!
Sorry, can't do it, unless the People
class (which should be called Person
) makes that method available. 抱歉,不能这样做,除非People
类(应称为Person
)使该方法可用。
A common practice is to make "private" methods start with an underscore. 一种常见的做法是使“私有”方法以下划线开头。 It does not 100% grant any security, but it at least gives other developers a hint that it is meant to be private. 它不会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
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.