Javascript,从对象构造函数中的另一个onclick调用函数

时间:2016-01-27 16:28:30

标签: javascript

我需要帮助从this.load内部调用thediv.onclick函数。我删除了大部分代码,所以它非常基本,但我真的找不到办法。这是我现在拥有的:

function CreatePizza(Name, Toppings) {
  this.n = Name;
  this.t = Toppings;
  this.load = function loadpizza() {
    //function that i want to be called
  }

  this.create = function button() {
    var thediv = document.createElement("div");
    thediv.onclick = function() {
      // Call this.load function here
    }
  }
}

5 个答案:

答案 0 :(得分:6)

问题是在onclick处理程序中,this会引用<div>,而不是您重复引用的其他this

两种可能的解决方案:

  1. 保存对所需this的引用:

    that = this;
    thediv.onclick = function () {
       that.load()
    };
    
  2. this绑定到您的函数:

    thediv.onclick = function () {
        this.load();
    }.bind(this);
    

    或者,如果这是您在该功能中唯一做的事情:

    thediv.onclick = this.load.bind(this);
    

答案 1 :(得分:2)

由于闭包,您可以简单地将this分配给变量并从中调用它!

function CreatePizza(Name, Toppings) {
  var self = this;
  this.n = Name;
  this.t = Toppings;
  this.load = function loadpizza() {
    //function that i want to be called
  }
  this.create = function button() {
    var thediv = document.createElement("div");
    thediv.onclick = function() {
      self.load();
    }
  }
}

我想提一下,在任何人开始使用火焰战之前更好的 - 并不一定更好 - 将事件附加到你的div(在我看来更优雅)是使用thediv.addEventListener('click', self.load, false)。不过只是旁注。

答案 2 :(得分:1)

在绑定事件之前备份this对象。

this.create = function button() {
    var that = this,
        thediv = document.createElement("div");

    thediv.onclick = function() {
        // Call this.load function here
        that.load();
    }
}

答案 3 :(得分:0)

function CreatePizza(Name, Toppings) {
  this.n = Name;
  this.t = Toppings;

  var foo = function loadpizza() {
    //function that i want to be called
  };


  this.load = foo;
  this.create = function button() {
    var thediv = document.createElement("div");
    thediv.onclick = function() {
      foo();
    }
  }
}

答案 4 :(得分:0)

function CreatePizza(Name, Toppings) {
  this.n = Name;
  this.t = Toppings;
  this.load = function loadpizza() {
    //function that i want to be called
  }
  var self = this;
  this.create = function button() {
    var thediv = document.createElement("div");
    thediv.onclick = function() {
      self.load()
    }
  }
}