致电"私人"来自" parent"的方法javascript中的对象

时间:2014-09-09 15:03:28

标签: javascript

在下面的代码中,我需要调用" 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!

1 个答案:

答案 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
  };
}