【问题标题】:Javascript Inheritance and the words "this" and "that" [duplicate]Javascript继承和单词“this”和“that”[重复]
【发布时间】:2016-04-25 02:35:38
【问题描述】:

我有一个类,我使用它的方法作为事件侦听器,所以我在方法中不使用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 的值在模式打开时为真,但在关闭时为假。

this.close这一行调试,我看到thatModal的一个实例,modalBookModalBook的一个实例。

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

【问题讨论】:

  • 你能为此制作一个小提琴吗?

标签: javascript class inheritance this


【解决方案1】:

那里发生的事情是ModalBook.prototype=new Modal() ModalBook 是“继承”Modal。变量在其范围内属于每个构造函数,并且属性被覆盖。所以:

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

我认为你有一个设计问题。可能对thats 使用不同名称的属性。

【讨论】:

    【解决方案2】:

    问题

    ModalBook.prototype = new Modal(); 这一行的意思是allnew ModalBook 指向一个单一的、新的Modal 对象,而这个Model 对象就是close 方法中的that

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


    修复

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

    传统上,这是一种更好的编码方式。

    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();
    

    【讨论】:

      猜你喜欢
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 2012-01-27
      • 2020-12-28
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多