मुझे किसी ऑब्जेक्ट विधि के भीतर जावास्क्रिप्ट इनलाइन फ़ंक्शन के भीतर "यह" संदर्भित करने में कठिनाई हो रही है।किसी ऑब्जेक्ट के इनलाइन फ़ंक्शन के भीतर से इसे एक्सेस करना
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
विधि में सबमिट फ़ंक्शन इनलाइन रखना चाहता हूं।
संभावित डुप्लिकेट [इस बंदरगाह को 'इस' कीवर्ड तक क्यों नहीं पहुंचता है? - jQuery] (http://stackoverflow.com/questions/3323189/why-doesnt-this-closure-have-access-to-the-this-keyword-jquery) –