我有一个嵌套if的函数。我该如何制作这个'指向构造函数。父

时间:2016-10-20 00:22:22

标签: javascript html html5 binding

我不确定我的"这个"指着。

我想在我的代码中包含以下内容,我希望"这个"在" this.getOwnerComponent()..."指向同一个"这个"作为我创建的一个新变量,它在k.getAggregation之外("你好..

我该怎么做?

代码:

function () {...

var c = this.getHat();
var agg = this.getOwnerComponent()

item.press: function() {
 var c = this.getHat(); //this" is not equal to the same "this" inside variable agg
}

2 个答案:

答案 0 :(得分:0)

您需要绑定该功能。在ES6中,您可以使用始终绑定的=>函数语法。 MDN documentation

而不是:

}.bind(oVBI));

尝试使用:

}.bind(this));

答案 1 :(得分:0)

如果您想要考虑较旧的浏览器,也可以使用旧式的构造函数。

function person(name){
    // properties
    this.name = name;

    this.greet = function(){
        alert("Hello, "+this.name);
    }
}

var p = new person("bob");
p.greet();