【问题标题】:Javascript method doesn't see object variableJavascript方法看不到对象变量
【发布时间】:2016-08-28 08:26:07
【问题描述】:
var Shape = function(type)
{
    this.type = type;

    addEventListener("resize", this.align);
}

Shape.prototype.align = function()
{
    alert(this.type);
}

.

var variable = new Shape('rectangle');

当我调整大小时,我想要提醒 rectangle 但它提醒 undefined

【问题讨论】:

  • alert(this)(或者更确切地说是记录到控制台),你看到了什么?
  • 添加到 BenG 的答案。在事件下,this 将指向 window
  • 我看到了[Object object]
  • 那是因为alert,试试console.log而不是alert

标签: javascript methods javascript-objects dom-events


【解决方案1】:

this 的值取决于函数的调用方式。执行时不能通过赋值来设置,每次调用函数时可能都不一样。 ES5 引入了 bind 方法来设置函数的 this 的值,不管它如何被调用 [MDN]

Function.prototype.bind() 方法创建一个新函数,在调用该函数时,会将其 this 关键字设置为提供的值。

var Shape = function(type) {
  this.type = type;
  addEventListener("resize", function() {
    this.align();
  }.bind(this));
  //OR addEventListener("resize", this.align.bind(this));  
}

Shape.prototype.align = function() {
  alert(this.type);
}


var variable = new Shape('rectangle');

【讨论】:

    【解决方案2】:

    您需要传递范围才能在resize 事件中使用this

    var Shape = function(type) {
      this.type = type;
      addEventListener("resize", this.align.bind(this));
    }
    
    Shape.prototype.align = function() {
      alert(this.type);
    }
    
    
    var variable = new Shape('rectangle');

    【讨论】:

      【解决方案3】:

      您需要使用variable.align(),因为您正在创建一个新对象。通过这样做,我得到了您的要求:'rectangle' 的警报。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-01
        • 1970-01-01
        • 2015-10-24
        • 1970-01-01
        • 2015-05-27
        • 1970-01-01
        • 2011-07-30
        • 1970-01-01
        相关资源
        最近更新 更多