如何使用Object.create在javascript中继承私有变量

Van*_*als 3 javascript oop inheritance

我有这个:

function Book (){
  this.width = 7;
  this.height = 10;
  var pages = 100;

  this.tear_page = function(){
    return --pages;
  }
}
function TechBook () {
  var pages = 50;
  this.open_book = function(){ return "Opened in page "+(pages/2); };
  return this;
}
var bBook = Object.create(new Book(), new TechBook());


console.log(bBook);
console.log(bBook.tear_page());
console.log(bBook.open_book());
Run Code Online (Sandbox Code Playgroud)

我不能让这个工作.我得到TechBook继承了Book中对本地/私有变量的访问权限,但仅限于Book函数.如果我添加新方法或覆盖它们,它们将无法再获取这些变量.我想知道是否有办法仍然可以从子类的方法访问这些变量,并在子类内创建新的私有变量.

如果这在某种程度上是不可能的,那么如果你想要继承,那就意味着你不能拥有私有变量,反之亦然.哦,顺便说一句,我知道chrome现在可以(感谢ES6)自然地实现类:class TechBook扩展了Book(){}和其他许多语言一样,但是由于支持仅限于此时的chrome的最新版本...我想知道是否还有其他方法可以解决这个问题.

eca*_*izo 5

您不能以任何语言继承私有,只能继承protected或public.

这个概念在javascript中不存在,但你可以在创建对象时模拟(properties = public,scope things = private);

解决方法可以添加一个属性,该属性执行返回对象范围的私有变量/函数的函数.

如果公开一个返回私有对象的方法,则可以修改它,因为你有返回的引用.

我喜欢这样做:

var SomeObject = function() {
    //private var one, can't access it outside of this scope
    var one = 1;

    /*private object anotherObject, can't access it directly
     but if you return it with a public function you can modify it.*/
    var anotherObject = {
        a : 'somevalue'
    };

    //public prop two, can access it outside of this scope.
    this.two = 2;

    //public method getOne, you can access it.
    this.getOne = function() {
       return one;
    };

    /* return private var anotherObject */
    this.getAnotherObject = function() {
       return anotherObject;
    };
};

var someObject = new SomeObject();
console.log(someObject.two); // print in console 2
console.log(someObject.getOne()); // print in console 1

var referencedObject = someObject.getAnotherObject();
console.log(referencedObject);
referencedObject.a = 'anotherValue';

console.log(someObject.getAnotherObject());
Run Code Online (Sandbox Code Playgroud)

小提琴