在对象方法中,我无法从
JavaScript内联函数中引用“this”.
- var testObject = {
- oThis : this,testVariable : "somestring",init : function(){
- console.log(this.testVariable); // outputs testVariable as expected
- this.testObject.submit(function(){
- var anotherThis = this;
- console.log(this.testVariable) // undefined
- console.log(oThis.testVariable) // undefined
- console.log(testObject.testVariable) // outputs testVariable
- console.log(anotherThis.testVariable) // undefined
- }
- }
如何从提交函数中访问this.testVariable?
我也使用jQuery,如果这有所作为.
我不知道这是否是最好的方法 – 也许我应该作为一个单独的函数提交,然后引用内联,像:
- init : function(){
- this.testObject.submit = this.submitForm;
- },submitForm : function(){
- // do validation here
- console.log(this.testVariable) // outputs testvariable
- .
- .
- .
- return valid;
- }
解决方法
一个常见的方法是将您想要的这个分配给一个局部变量.
- init: function() {
- var _this = this;
- this.testObject.submit(function() {
- console.log(_this.testVariable); // outputs testVariable
- });
- }