Javascript 方法看不到对象变量

Javascript method doesn't see object variable

本文关键字:变量 对象 看不到 方法 Javascript      更新时间:2023-09-26
var Shape = function(type)
{
    this.type = type;
    addEventListener("resize", this.align);
}
Shape.prototype.align = function()
{
    alert(this.type);
}

.

var variable = new Shape('rectangle');

当我调整大小时,我想要警报矩形,但它警报未定义

您需要传递作用域才能在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');

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

this的值由函数的调用方式决定。它不能在执行期间通过赋值设置,并且每次调用函数时它可能会有所不同。ES5 引入了绑定方法来设置函数的值 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');