Javascript AddEventListener到本地类而不是这个

时间:2018-01-09 08:29:53

标签: javascript

来自C ++我对Javscript中的“this”关键字感到困惑。

我想要做的是在子类中添加eventlistener时使用this关键字。但是我注意到这似乎没有用,所以我想知道我是如何做这项工作的。

let myClass = new Class();
myClass.AddSubClass();

function Class()
{
    this.array = new Array();

  this.AddSubClass = function()
  {
    let sub = new SubClass();

    this.array.push(sub);
  }
}

function SubClass()
{
  let maindiv = document.getElementById("Main");
  this.btn = document.createElement("button");
  this.btn.innerHTML = "Button";
  this.btn.addEventListener("click", function() { this.Upgrade(); });

  maindiv.appendChild(this.btn);

  this.Upgrade = function()
  {
    //Do something
  }
}

这是一个我写的可能有错误的快速示例,但它仍然应该显示我想要完成的任务。

我仍然对Javscript 非常新,并试图了解我的方法。 希望有一个简单的答案。

每当我按下按钮时,我的错误是什么。我得到“this.Upgrade()”不是一个函数。

2 个答案:

答案 0 :(得分:1)

在事件处理程序中,this对象是处理程序所在的对象。在您的情况下,button元素。

要使用SubClass对象,您需要使用另一个变量,在构造函数中为其分配对SubClass对象的引用:

function SubClass()
{
    // ...
    self = this;
    // ...
    this.btn.addEventListener("click", function() { self.Upgrade(); });
    // ...
}

答案 1 :(得分:1)

在JS中,this并没有坚持它所定义的类,而是对上下文敏感。

function foo(label="") {
  console.log(label, this);
}

let a = {foo, id: "a"};
let b = {foo, id: "b"};

//usually "this" is the object the function is executed of
a.foo();
b.foo();

//you can also pass the context
var c = {id:"c"};
foo.call(c, "c");
foo.apply(c, ["here", "you", "can", "pass", "an", "array", "of", "arguments"]);

//you can bind it
var d = {foo: foo.bind(c), id:"d"};
d.foo("calling on 'd' but 'this' is still 'c':");

//if you just call the function, the context is the global object
foo("plain call:");

在您的情况下,您必须将对象存储在this中,或者您可以使用没有自己this的箭头功能。

var _this = this;
this.btn.addEventListener("click", function() { _this.Upgrade(); });

this.btn.addEventListener("click", () => this.Upgrade() );

Sidenote,来自C ++:
调用函数时JS不关心参数的不匹配。如果传递的参数太多,则忽略其余参数。如果传递给少数,则retaininig参数将设置为undefined

返回值相同,如果函数没有明确地返回值,则会隐含地返回undefined值。 除了使用new关键字调用的构造函数之外,您要么返回一个对象(基元被忽略),要么隐式重新调整值为this;