简体   繁体   English

为什么我不能在我的对象文字中访问this.property?

[英]why can't I access this.property in my object literal?

I've just been restructuring my code into objects and using the this keyword, I've got this problem whereby, setting the prop works, but then when the second method fires, myProp is undefined. 我刚刚将我的代码重构为对象并使用this关键字,我遇到了这个问题,设置prop工作,但是当第二个方法触发时, myProp是未定义的。 I've noticed if I use myObj to set and get rather than this it works fine. 我注意到如果我使用myObj来设置和获取而不是这样它可以正常工作。 What's the difference here? 这有什么区别? What am I doing wrong? 我究竟做错了什么? I though this was referring to the instance of which there is only one which was automatically instantiated by the object literal. 我虽然这是指其中只有一个由对象文字自动实例化的实例。

var myObj = {
    SetProp: function (id) {
        this.myProp = "abc";
        Ajax.GetJSONAfterStandardLogic(Utility.PrefixURL("/ajax/mymethod"), this.SetPropSuccess);
    },
    SetPropSuccess: function (response) {
        console.log("test " + this.myProp);
    }
}

Likely because when you call those functions, this is not the object. 可能因为当你调用这些函数时, this不是对象。 this is the binding with which the function was called. this是调用函数的绑定。

A bit more code to demonstrate how you're calling the function would be useful, but you can make it work by using: 更多代码来演示如何调用函数会很有用,但是你可以通过使用它来使它工作:

myObj.SetProp.call(myObj, id)

This binds myObj as this , for the SetProp function call. 这种结合MyObj中为this ,对于SetProp函数调用。

If you put console.log(this) in either of those functions, you'll probably find that this is not what you're expecting. 如果你把console.log(this)放在其中任何一个函数中,你可能会发现this不是你所期望的。

When your callback function is executed, it's in a different scope. 执行回调函数时,它处于不同的范围。 As such "this" references that scope and your "myProp" is not defined. 因此,“this”引用了范围,并且未定义“myProp”。 That's why using myObj.myProp works - the scope remains valid. 这就是使用myObj.myProp工作的原因 - 范围仍然有效。

Cheers 干杯

The this variable is set according to how a function is called. 根据函数的调用方式设置this变量。 When you use objectReference.method() "dot" syntax this will automatically be set to the object. 当您使用objectReference.method() “点”语法this将自动设置到对象。 You can also call a function and explicitly set this to some other object by using .call() or .apply() . 您也可以调用一个函数,并明确设定this使用一些其他物体.call().apply()

In your case, when you pass this.SetPropSuccess as a callback function you are passing a reference to the function and when it is then called by GetJSONAfterStandardLogic() it is not called in a way that sets this to your object (most likely it will be equal to window ). 在你的情况,当你通过this.SetPropSuccess为你传递给函数的引用,当它然后被称为一个回调函数GetJSONAfterStandardLogic()那就不叫在设置方式this给你的对象(最有可能将等于window )。 You can work around the problem by saving a reference to the object in a local variable of SetProp() : 您可以通过在SetProp()的局部变量中SetProp()对象的引用来解决此问题:

var myObj = {
    SetProp: function (id) {
        var self = this;
        this.myProp = "abc";
        Ajax.GetJSONAfterStandardLogic(Utility.PrefixURL("/ajax/mymethod"),
                                       function() { self.SetPropSuccess(); });
    },
    SetPropSuccess: function (response) {
        console.log("test " + this.myProp);
    }
}

Through the magic of closures, the anonymous function that I've added as a callback to pass to GetJSONAfterStandardLogic() has access to the variables in its containing scope SetProp() even after SetProp() has finished executing . 通过闭包的魔力, 即使在 SetProp() 完成执行 ,我作为回调传递给GetJSONAfterStandardLogic()的匿名函数也可以访问其包含范围SetProp()的变量。

Bottom line is that you have to get used to this in JavaScript working very differently to the way it works in class-based OO languages like Java and C#. 最重要的是,你必须在JavaScript中习惯this方式与它在基于类的OO语言(如Java和C#)中的工作方式有很大不同。 JavaScript is still OO, but these differences usually trip up people coming to the language from Java or C#. JavaScript仍然是OO,但这些差异通常会使人们从Java或C#转向语言。

Further reading: https://developer.mozilla.org/en/JavaScript/Reference/Operators/this 进一步阅读: https//developer.mozilla.org/en/JavaScript/Reference/Operators/this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM