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

时间:2015-04-30 16:12:35

标签: 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());

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

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

2 个答案:

答案 0 :(得分:5)

您不能以任何语言继承私人,只能继承受保护或公共。

这个概念在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());

Fiddle

答案 1 :(得分:1)

引用prototype inheritanceObject.create属性参数的基础知识。

根据您的示例实施

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

  this.tear_page = function(){
    return --this.pages;
  }
  this.init = function() {
    return this
  }
}

Book.prototype = {
  open_book: function(){ return "Opened in page "+(this.pages/2) }
}


var bBook = Object.create(new Book(), {pages: { value: 50 } }).init();


console.log( new Book())              // { width: 7, height: 10, pages: 100, tear_page: [Function], init: [Function] }
console.log( bBook )                  //{}
console.log( bBook.width )            //->7              
console.log( bBook.height )           //-> 10             
console.log( bBook.pages )            // -> 50             
console.log( bBook.tear_page())       //-> 49
console.log(bBook.open_book())       //-> Opened in page 25