【问题标题】:How can I access the super of the super class in JS?如何在 JS 中访问超类的超类?
【发布时间】:2013-06-19 14:08:03
【问题描述】:

该代码非常具有解释性。我在做什么是错的。在A 对象方法中声明的对象的onclick 事件中,如何访问A 对象的a 属性?

function A(){
    this.a = 0;
};

A.prototype.myfun= function(){
    var b = document.getElementsByClassName("myclassName");
    b[0].onclick = function(e){
    //How can I get the a property of the A object in here?
        this.a = 1;
    }
};

我可以以某种方式将其作为这样的参数传递吗?

b[0].onclick = function(e, this){

【问题讨论】:

标签: javascript class object dom-events


【解决方案1】:

由于函数中的this 引用了函数本身,因此您可以做两件事。传递引用,或创建一个您不会覆盖的变量来表示 this

function A(){
    this.a = 0;
};

A.prototype.myfun= function(){
    var self = this;
    var b = document.getElementsByClassName("myclassName");
    b[0].onclick = function(e){
        self.a = 1;
    }
};

【讨论】:

  • 这真是太棒了!
猜你喜欢
  • 1970-01-01
  • 2010-12-13
  • 2013-01-04
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-24
  • 1970-01-01
相关资源
最近更新 更多