Javascript继承和;这";及;那";

Javascript继承和;这";及;那";,javascript,class,inheritance,this,Javascript,Class,Inheritance,This,我有一个类,我使用它的方法作为事件监听器,所以我在方法中不使用this,而是使用that 这是基类: function Modal(){ var that = this; this.opened = false; this.open = function(){ that.opened = true; var id = this.id; // more code }; this.close =

我有一个类,我使用它的方法作为事件监听器,所以我在方法中不使用
this
,而是使用
that

这是基类:

function Modal(){
     var that = this;
     this.opened = false;
     this.open = function(){ 
         that.opened = true;
         var id = this.id;
         // more code
     };
     this.close = function () { 
         if (that.opened) // do something;
     };
}
这是继承的类:

function ModalBook(){
     var that = this;
     this.open = function(){ 
         that.opened = true;
         var id = this.id;
         // more code
     };
}
ModalBook.prototype = new Modal();

var modalBook = new ModalBook();
现在,打开模式时,
modal.opened
的值为true,但关闭模式时,该值为false

this.close
行上调试时,我看到
那是
Modal
的一个实例,
modalBook
那是
modalBook
的一个实例


因此,我的问题是:如何在
modalBook
的两种方法中保留
this
的值?

modalBook.prototype=new Modal()
modalBook
中发生的事情是“继承”
Modal
。变量在其作用域中属于每个构造函数,属性被覆盖。因此:

  • 模式中的
    将在本地停留在
    模式中
  • ModalBook
    中的
    将是
    ModalBook
  • 但是唯一存在的
    open()
    方法是
    ModalBook.open()
    (您正在覆盖另一个方法),其中
    ModalBook
    的一个实例,而另一个
    不在该范围内

我想你的设计有问题。可能会使用不同名称的属性来解决问题

ModalBook.prototype=new Modal()
表示所有新的ModalBook指向一个单一的新模态对象,该模型对象是close方法中的

不会为每个新的
ModalBook
重新创建此对象。这是原型继承


修复

如果操作正确,则无需捕获

传统上,这里有一种更好的编码方法

var Modal = function(){ return this; };
Modal.prototype = {
   opened : false,
   open : function(){ 
      this.opened = true;
      var id = this.id;
      // more code
  },
  close : function () { 
      if (this.opened) // do something;
  },
};

// Old IE may not have Object.assign or Object.create. shims available.
var ModalBook = function(){ Modal.call( this ); return this; };
ModalBook.prototype = Object.assign( Object.create( Modal.prototype ), { 
   open : function(){
      this.opened = true;
      var id = this.id;
      console.log( 'open2' );
   } 
} );

var modalBook = new ModalBook();

无构造函数

或者如果你不喜欢使用构造函数,就像我一样

/* In ES6.  Runs on Chrome, Firefox, Edge, Safari.  Use Babel to run on IE. */

const Modal = {
   opened: false,
   create     () { return Object.create( Modal ).initialise(); },
   initialise () { return this; },
   open       () { /* ... */ },
   close      () { /* ... */ },
};

const ModalBook = {
   __proto__ : Modal,
   create     () { return Object.create( ModalBook ).initialise(); },
   open       () { /* ... */ },
};

var modalBook = ModalBook();

你能为这个做一把小提琴吗?